您的位置:首页 > 编程语言 > C#

c# 中Linq Lambda 的ToLookup方法的使用

2018-02-27 11:50 591 查看
同样直接上代码:

List<Student> ss = new List<Student>();
Student ss1 = new Student() { Id = 1, Age = 1, Name = "11" };
Student ss2 = new Student() { Id = 1, Age = 1, Name = "11" };
Student ss3 = new Student() { Id = 2, Age = 2, Name = "22" };
Student ss4 = new Student() { Id = 2, Age = 2, Name = "22" };
Student ss5 = new Student() { Id = 2, Age = 2, Name = "22" };
Student ss6 = new Student() { Id = 3, Age = 3, Name = "33" };
ss.Add(ss1);
ss.Add(ss2);
ss.Add(ss3);
ss.Add(ss4);
ss.Add(ss5);
ss.Add(ss6);
//var aa = ss.GroupBy(m => new { m.Id, m.Age }).Select(group => new {group.Key.Id,group.Key.Age,count = group.Count()}).ToList();
//foreach (var item in aa)
//{
//    Console.WriteLine(item.Id + "||" + item.Age + "||" + item.count);
//}

var dic = ss.ToLookup(m => m.Id);
foreach (var item in dic)
{
Console.WriteLine("学生ID号:" + item.Key);

foreach (var item1 in item)
{
Console.WriteLine("\t\t" + item1 + " || " + item1.Age + " || " + item1.Name);
}
}


执行结果:

学生ID号:1
Test.Student || 1 || 11
Test.Student || 1 || 11
学生ID号:2
Test.Student || 2 || 22
Test.Student || 2 || 22
Test.Student || 2 || 22
学生ID号:3
Test.Student || 3 || 33


其中item1是student实例。

此方法的作用和ToDictionary类似,但避免Dictionary类型key子段不能重复的问题。

同时也可用于按某字段Group By排序的场景,且相对后者的优势是带有索引便于操作(其实Group By的数据后面添加ToList()后也很方便,当然这是后话了)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: