2010-12-20 145 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