2013-06-25 14 views
2

我有這樣一個字符串,因此 串DIR =「視頻/視頻/關於/視頻/視頻/」聚集的String []抓住第一不同,但我想它搶過去不同

當我運行通過我的linq聲明進行分割並運行,它抓取了第一個不同的項目,所以video/About,但我希望它抓住最後一個可能的區別。所以關於/視頻

所以「視頻/視頻/關於/視頻/視頻/」應該等於公司/視頻

但「視頻/視頻/關於/關於」應該還是等於視頻/關於

repeat = domain + dir.Split('/') 
.Where(x => keep.Contains(x)).Distinct() 
.Aggregate((gi, j) => gi + "/" + j) + repeat.Substring(lastSlash); 
+1

'的string.join( 「/」,repeat.GroupBy(X => x).OrderBy(x => x.Count())。Select(x => x.Key))'也許? – Polity

回答

3

您可以嘗試Reverse兩次:

string result = domain + dir.Split('/') 
     .Where(x => keep.Contains(x)) 
     .Reverse() //once before Distinct 
     .Distinct() 
     .Reverse() //and again afterwards 
     .Aggregate((gi, j) => gi + "/" + j) + repeat.Substring(lastSlash); 

所以video/video/About/video/video/結果About/video/

video/video/About/About結果video/About/

1

考慮使用Select的過載,該過載將索引作爲轉換的一部分(記錄爲here)。

如果您想要每個不同元素的最後一個不同元素,則可以嘗試相應地使用GroupBy對每個IGrouping進行排序,並抓取每個組的正確元素。

repeat = domain + dir.Split('/') 
.Select((word, index) => Tuple.Create(word, index)) 
.Where(x => keep.Contains(x.Item1)) 
.GroupBy(x => x.Item1) 
.Select(g => g.OrderByDescending(x => x.Item2).First()) 
.OrderBy(x => x.Item2) 
.Select(x => x.Item1) 
.Aggregate((gi, j) => gi + "/" + j) + repeat.Substring(lastSlash); 

在這裏,我們將每個單詞與其索引(使用上面提到的Select過載)耦合。然後我們篩選出感興趣的話。我們現在使用GroupBy來生成IEnumerable<IGrouping<string, Tuple<string, int>>,而不是使用Distinct。由於IGrouping本身實現IEnumerable,我們通過在按索引排序時獲取每個IGrouping的最後一個元素,將我們的IGroupings列表投影到Tuple<string, int>列表中。然後我們通過索引來命令我們新的Tuples列表,以便這些單詞保持順序,並且投影到元組的string部分。

+2

嗯,我不能扭轉整個字符串,因爲像video/video/about/about這樣的東西如果被顛倒的話會顯示爲 關於/ video,我只想抓住最後的不同。 – Spooks

+1

@Spooks我已經更新了適合更復雜版本的答案。 –

相關問題