Reputation: 91
I'd like to split my data to lists by an attribute's value and check all the combination options between the lists' items. My problems are that I don't know how many list I'll get and if there is a better way to do that beside this way:
var a = Data.Descendants("value").Where(x => x.Attribute("v").Value == "1").ToList(); var b = Data.Descendants("value").Where(x => x.Attribute("v").Value == "2").ToList(); var c = Data.Descendants("value").Where(x => x.Attribute("v").Value == "3").ToList();
foreach (var tempA in a) { foreach (var tempB in b) { foreach (var tempC in c) { DO SOMETHING; } } }
EDIT:
I'd like to check my items from one data source (var items = new List<string>{"1","1","2","3","2","1","3","3","2"}
)
Now I'd like to split this list to 3 lists (list a = "1","1","1" - list b = "2","2","2" - list c = "3","3","3"
)
In this step what I'm trying to do is to check all the combination from one item in one list to the other items in the other lists.
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]
.
.
Thanks!
Upvotes: 2
Views: 229
Reputation: 4532
You can do this,following the line of thinking of romoku and 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());
}
For your new edit list of Strings this will do it
List<List<string>> NewList = new List<List<string>>();
foreach (var item in OriginalList.GroupBy(x => x))
{
NewList.Add(item.ToList());
}
Upvotes: 0
Reputation: 21255
You can use GroupBy
to group your elements. Then you can create combinations using 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
}
e.g.
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 }));
Upvotes: 0
Reputation: 1171
Could you try using the LINQ GroupBy method? Some examples are here:
Upvotes: 0