2013-06-19 49 views
2

我想通過屬性的值將數據拆分爲列表,並檢查列表項目之間的所有組合選項。 我的問題是,我不知道我會得到多少列表,如果有更好的方法可以這樣做:操作c列表中的n個列表的所有列表項選項

var a = Data.Descendants(「value」)。其中(x => x.Attribute(「v」)。Value ==「1」)。ToList(); var x = Data.Descendants(「value」)。其中(x => x.Attribute(「v」)。Value ==「2」)。ToList(); var x = Data.Descendants(「value」)。其中(x => x.Attribute(「v」)。Value ==「3」)。ToList();

的foreach(在VAR TEMPA) { 的foreach(b中VAR tempB) { 的foreach(在C VAR tempC) { 做某事; }} }

編輯: 我想從一個數據源檢查我的項目(var items = new List<string>{"1","1","2","3","2","1","3","3","2"}

現在我想把這個列表拆分到3所列出(list a = "1","1","1" - list b = "2","2","2" - list c = "3","3","3"

在這一步中,我試圖做的是檢查從一個列表中的一個項目到其他列表中的其他項目的所有組合。

a[0] with b[0] c[0] 
a[0] with b[0] c[1] 
a[0] with b[0] c[2] 
a[0] with b[1] c[0] 
. 
. 
b[1] with a[2] c[2] 
. 
. 

謝謝!

回答

0

你可以嘗試使用LINQ GroupBy方法嗎?一些例子在這裏:

LINQ GroupBy examples

+0

謝謝,這解決了第一個問題。你有第二個想法嗎?如何運行項目之間的所有組合 – Asaf

+0

來自@Romoku的SelectMany/ForEach建議是否解決了這個問題? – ChrisC

0

您可以使用GroupBy將你的元素。然後你可以使用Linq創建組合。

var grouping = Data.Descendants("value") 
        .GroupBy(x => x.Attribute("v").Value); 

var combinations grouping.SelectMany(x => 
           grouping.Select(y => 
            new { Group = x, Combination = y })); 

foreach(var c in combinations) 
{ 
    //Do Something 
} 

例如,

public class Pair 
{ 
    public string A { get; set; } 
    public string B { get; set; } 
} 

var pairs = new List<Pair>(); 
pairs.Add(new Pair { A = "1", B = "2" }); 
pairs.Add(new Pair { A = "1", B = "3" }); 
pairs.Add(new Pair { A = "1", B = "4" }); 
pairs.Add(new Pair { A = "2", B = "1" }); 
pairs.Add(new Pair { A = "2", B = "2" }); 
pairs.Add(new Pair { A = "2", B = "3" }); 

var grouping = pairs.GroupBy(x => x.A); 

var combinations = grouping.SelectMany(x => 
           grouping.Select(y => 
            new { Group = x, Combination = y })); 

Groupings result

0

你可以做到這一點,以下romoku的思維和chrisC

//new list of lists to hold new information. 
List<List<Descendants>> NewList = new List<List<Descendants>>(); 

foreach (var item in Data.Descendants.GroupBy(x => x.Attribute("v").Value)) 
{ 
    NewList.Add(item.ToList()); 
} 

字符串的新的編輯列表的線,這將做到這一點

List<List<string>> NewList = new List<List<string>>(); 

foreach (var item in OriginalList.GroupBy(x => x)) 
{ 
     NewList.Add(item.ToList()); 
}