2010-12-20 147 views
0

親愛的朋友們在得到運行的組合,這是像我以前How to get moving combination from two List<String> in C#?C#:如何從兩個List <String>基於主列表

我有一個masterlist和兩個的childList類似問題下面

 List<String> MasterList = new List<string> { "A", "B", "C", "D", "E" }; 
     List<String> ListOne = new List<string> { "A", "B", "C" }; 
     List<String> ListTwo = new List<String> { "B", "D" }; 

我只需要從該上面的列表中我使用像(前一個問題的回答(感謝丹尼·陳))獲得運行中的組合

 List<String> Result = new List<string>(); 
     Result = ListOne.SelectMany((a, indexA) => ListTwo 
            .Where((b, indexB) => ListTwo 
            .Contains(a) ? !b.Equals(a) && indexB > indexA : 
            !b.Equals(a)).Select(b => string.Format("{0}-{1}", a, b))).ToList(); 

這樣的結果列表將包含

 "A-B" 
     "A-D" 
     "B-D" 
     "C-B" 
     "C-D" 

現在我的問題是排序問題

在上述結果的第四個條目是C-B但它應該是B-C。因爲在MasterListC之後是B

如何在我現有的linq中做到這一點。

請幫我做到這一點。

+1

我不明白爲什麼MasterList的。而且,輸出不應該是:「A-B,A-D,B-D,C-D」? – 2010-12-20 17:59:52

+0

@ AS-CII:Friend,在ResultList中,這個項目應該是'MasterList'順序。即它應該以主列表順序開始 – 2010-12-20 18:03:49

+1

上述代碼不會產生「B-D」。 – 2010-12-20 19:13:14

回答

1

這裏的確切要求並不十分清楚,MasterList也規定兩項中的哪一項應首先出現?那麼X1-X2列表的順序呢?即應該B-C出現在B-D之前,因爲C在MasterList中出現在D之前?

總之,這裏的東西,產生你自找的,到目前爲止結果:

List<String> MasterList = new List<string> { "A", "B", "C", "D", "E" }; 
List<String> ListOne = new List<string> { "A", "B", "C" }; 
List<String> ListTwo = new List<String> { "B", "D" }; 

ListOne.SelectMany(i => 
ListTwo.Where(i2 => i != i2) 
     .Select(i2 => 
      { 
       if (MasterList.IndexOf(i) < MasterList.IndexOf(i2)) 
        return string.Format("{0}-{1}", i, i2); 
       else 
        return string.Format("{0}-{1}", i2, i); 
      } 
     )); 

輸出:

A-B 
A-D 
B-D 
B-C 
C-D 
+0

+1不錯的解決方案。這就是我要找的 – 2010-12-20 19:52:39