我从MySQL表中得到结果如下。 每次数据的结果都不同,我需要将它分组以分离新的List< int>。 DataTable中的数据列表:
id_task id_supplier id_source_ps
1 77 3
2 71 3
3 77 1
4 77 2
5 72 3
6 72 2
7 77 3
8 72 3
9 71 1
10 72 3
将id_task分组到新列表的条件与id_supplier和id_source_ps相同!
什么方法(LINQ?)用于得到结果 - 如本例所示 - 七个新List< int>
name of list id_task_in
group1 9
group2 2
group3 6
group4 5,8,10
group5 3
group6 4
group7 1,7
答案 0 :(得分:1)
您正在寻找GroupBy
。您需要GroupBy
您的密钥,然后Select
您的结果。以下是使用您的数据的示例 -
public class Program
{
public static void Main(string[] args)
{
var list = new List<Item>
{
new Item { task = 1, supplier = 77, source = 3 },
new Item { task = 2, supplier = 71, source = 3 },
new Item { task = 3, supplier = 77, source = 1 },
new Item { task = 4, supplier = 77, source = 2 },
new Item { task = 5, supplier = 72, source = 3 },
new Item { task = 6, supplier = 72, source = 2 },
new Item { task = 7, supplier = 77, source = 3 },
new Item { task = 8, supplier = 72, source = 3 },
new Item { task = 9, supplier = 71, source = 1 },
new Item { task = 10, supplier = 72, source = 3 }
};
var groupBy =
list
.GroupBy(x => new { first = x.source, second = x.supplier})
.Select(x => new { name = x.Key, items = x.Count() });
foreach (var g in groupBy)
{
Console.WriteLine(g);
}
}
}
public class Item
{
public int task;
public int supplier;
public int source;
}
打印
{ name = { first = 3, second = 77 }, items = 2 }
{ name = { first = 3, second = 71 }, items = 1 }
{ name = { first = 1, second = 77 }, items = 1 }
{ name = { first = 2, second = 77 }, items = 1 }
{ name = { first = 3, second = 72 }, items = 3 }
{ name = { first = 2, second = 72 }, items = 1 }
{ name = { first = 1, second = 71 }, items = 1 }
您可以将此示例用作起点。要完成您的需要,只需将.Count()
更改为.Aggregate()
,即可返回任务ID的列表,而不是任务ID的数量。如果您愿意,也可以更改密钥以匹配“组1”“组2”,但您需要为每个组编写一些标准方法(例如"group"+(index+1).ToString())
。
答案 1 :(得分:0)
以汤姆的回答为基础:
public static void Main(string[] args)
{
var list = new List<Item>
{
new Item { task = 1, supplier = 77, source = 3 },
new Item { task = 2, supplier = 71, source = 3 },
new Item { task = 3, supplier = 77, source = 1 },
new Item { task = 4, supplier = 77, source = 2 },
new Item { task = 5, supplier = 72, source = 3 },
new Item { task = 6, supplier = 72, source = 2 },
new Item { task = 7, supplier = 77, source = 3 },
new Item { task = 8, supplier = 72, source = 3 },
new Item { task = 9, supplier = 71, source = 1 },
new Item { task = 10, supplier = 72, source = 3 }
};
var groupBy = list.GroupBy(x => new { first = x.supplier, second = x.source})
.OrderBy(x=>x.Key.first).ThenBy(x=>x.Key.second)
.Select((x,i) => new { name = "group"+(i+1), items = x.Select(y=>y.task) });
foreach (var g in groupBy)
{
Console.WriteLine("{0} {1}",g.name,String.Join(",",g.items.Select(x=>x.ToString())));
}
}
public class Item
{
public int task;
public int supplier;
public int source;
}
将返回:
group1 9
group2 2
group3 6
group4 5,8,10
group5 3
group6 4
group7 1,7
我将最终输出保留为IEnumerable<string,IEnumerable<int>>
,因为我通常更喜欢这样。您可以轻松地将string.join移动到select中,如果您希望将其改为IEnumerable<string,string>
。