Lambda&Linq
阅读原文时间:2023年07月10日阅读:2

var list = new List
{
new Model { Id = , UserName = "张三", Password = "", Email = "zhang3@yoy.com"},
new Model { Id = , UserName = "李四", Password = "", Email = "li4@yoy.com"},
new Model { Id = , UserName = "王五", Password = "", Email = "wang5@yoy.com"},
new Model { Id = , UserName = "赵六", Password = "", Email = "zhao6@yoy.com"},
};

        //Add():添加单个,新加的数据将会在列表的最末端  
        //直译:添加  
        list.Add(new Model { Id = , UserName = "孙七", Password = "", Email = "sun7@yoy.com"});  
        //AddRange():添加多个,新加的数据将会在列表的最末端  
        //直译:范围添加  
        list.AddRange(new List<Model>  
        {  
            new Model { Id = , UserName = "刘一", Password = "", Email = "liu1@yoy.com"},  
            new Model { Id = , UserName = "陈二", Password = "", Email = "chen2@yoy.com"},  
        });  
        //Insert():添加单个,新加的数据将会在指定的索引位置,用法与Add()类似  
        //InsertRange():添加多个,新加的数据将会在指定的索引位置,AddRange()类似  
        //能指定位置插入数据,但是开销要大于Add/AddRange,目标集合越大,开销就越大  
        list.Insert(, new Model { Id = , UserName = "周八", Password = "", Email = "zhou8@yoy.com" });  
        list.InsertRange(, new List<Model>  
        {  
            new Model { Id = , UserName = "吴九", Password = "", Email = "wu9@yoy.com"},  
            new Model { Id = , UserName = "郑十", Password = "", Email = "zheng10@yoy.com"},  
        });

        //将集合转化为指定的类型  
        var enumerable = list.AsEnumerable();//IEnumerable<T>类型  
        var queryable = list.AsQueryable();//IQueryable<T>类型  
                                           //IEnumerable类型内存迭代,  
                                           //IQueryable类型表达式解析,语法树动态解析,延后查询  
                                           //AsQueryable()常用于存在不确定的查询条件之前

        //Distinct():去重复,与sql中distinct相同,返回值为IEnumerable<T>类型  
        list = list.Distinct().ToList();

        //ForEach():循环方法,括号中并非添加bool条件,而是进行操作  
        list.ForEach(f => f.Id += );  
        list.ForEach(f =>  
        {  
            if (f.Id == ) f.Password = "";  
            else f.Id -= ;  
        });                    

        //Find():Find一类方法为Framework2.0时期的产物,现基本不用  
        var find = list.Find(f => f.Id == );  
        var findAll = list.FindAll(f => f.Id == );

        //FirstOrDefault():第一个或者是默认值,返回值肯能为null  
        //Framework3.5时期的产物,运用范围更广,支持IEnemerable<T>,但速度比Find较慢  
        //First():与FirstOrDefault()用法相似,但不会返回null,而抛出异常  
        var first = list.First();  
        var firstOrDefault = list.FirstOrDefault();  
        //最后一个,原理同First()/FirstOrDefault()  
        var last = list.Last();  
        var lastOrDefault = list.LastOrDefault();  
        //唯一的一个,原理同First()/FirstOrDefault(),但如果出现重复数据,则抛异常  
        var single = list.Single(s => s.Id == );  
        var singleOrDefault = list.SingleOrDefault(s => s.Id == );

        var newList = new List<NewModel>  
        {  
            new NewModel { UserId = , Address = "Address", CellPhone = "", Country = "中国"},  
            new NewModel { UserId = , Address = "Address", CellPhone = "", Country = "西班牙"},  
            new NewModel { UserId = , Address = "Address1", CellPhone = "", Country = "中国"},  
            new NewModel { UserId = , Address = "Address2", CellPhone = "", Country = "美国"},  
        };  
        //Join():关联,相当于sql中的inner join  
        //写法:第一集合.Join(第二集合,第一的关联值,第二的关联值,(第一集合名,第二集合名)=>查询结果)  
        //查询结果可自定义类型,返回值为IEnemerable<查询结果>  
        var joinInfo = list.Join(newList, l => l.Id, nl => nl.UserId, (l, nl) => new { l, nl }).ToList();  
        var joinLinq = (from l in list  
                        join nl in newList on l.Id equals nl.UserId  
                        select new { l, nl }).ToList();

        //GroupBy():按照指定参数进行分组,返回值类型为IEnemerable<IGrouping<string,T>>  
        var groupInfo = newList.GroupBy(g => g.Country).ToList();  
        var groupLinq = (from nl in newList  
                         group nl by nl.Country into nlGroup  
                         select nlGroup);

        //GroupJoin():左关联,相当于sql中的left join后进行了一定的分组,等于主表.Join(子表.GroupBy())  
        //按照一定规律分组后进行关联,形成一对多的匿名类型,IEnemerable<{T1, IEnemerable<T2>}>  
        //写法与Join相同:第一集合.GroupJoin(第二集合,第一的关联值,第二的关联值,(第一集合名,第二集合名)=>查询结果)  
        //查询结果可自定义类型,返回值为IEnemerable<查询结果>  
        //第一集合为主集合,第二集合为子集合,子集合条数可能为0  
        var groupJoin = list.GroupJoin(newList, l => l.Id, g => g.UserId, (l, g) => new { l, g }).ToList();  
        var groupJoinLinq = (from l in list  
                         join nl in newList on l.Id equals nl.UserId into g  
                         select new { l, g }).ToList();

        //DefaultIfEmpty():查询默认或空实体,返回值为IEnumerable<T>类型,常用于做关联  
        var defaultList = list.DefaultIfEmpty().ToList();

        //左关联变形:Join()/GroupJoin()加DefaultIfEmpty()方法实现  
        //先将两集合进行GroupJoin(),之后将查询结果中的子集合DefaultIfEmpty()  
        //注:此处的做关联与sql中的左关联有所不同,此处的左关联为一对一或一对null  
        var leftJoin = list.GroupJoin(newList, l => l.Id, g => g.UserId, (l, g) => new { l, g = g.DefaultIfEmpty() }).ToList();  
        var leftLinq1 = (from l in list  
                         join nl in newList on l.Id equals nl.UserId into g  
                         select new { l, g = g.DefaultIfEmpty() });  
        var leftLinq2 = (from l in list  
                        join nl in newList on l.Id equals nl.UserId into nlJoin  
                        from g in nlJoin.DefaultIfEmpty()  
                        select new { l, g });

        //All():集合中的数据是否全部符合条件  
        //直译:全部  
        var trueAll = list.All(a => a.Id > );  
        var falseAll = list.All(a => a.Id > );

        //Any():集合中是否含有符合条件的数据  
        //直译:存在  
        var trueAny = list.Any(a => a.Id == );  
        var falseAny = list.Any(a => a.Id == );

        //Min()/Max():最小值/最大值  
        //筛选出指定值/指定算法为最小/最大的数据,返回单条  
        //可与左关联/排序等活用  
        var minList = list.Min(m => m.Id);  
        var maxList = list.Max(m => m.Email.Length);

        //OrderBy()/OrderByDescending():正序/逆序  
        //按照指定字段/指定算法进行正序/逆序的排序  
        //可与左关联、分页等活用  
        var orderBy = list.OrderBy(o => o.Id).ToList();  
        var orderByLinq = (from l in list  
                           orderby l.Id  
                           select l).ToList();  
        var orderByDesc = list.OrderByDescending(o => o.Email.Length);  
        var orderByDescLinq = (from l in list  
                               orderby l.Email.Length descending  
                               select l).ToList();  
        //Reverse():反转排序,List无法适用  
        var reverse = list.Where(w => true).Reverse().ToList();

        //Select():将一个实体中的数据转为另一个实体  
        //返回值类型为:IEnumerable<T>  
        var select1 = list.Select(s => s.Id).ToList();//指定字段/值  
        var select2 = list.Select(s => new { s.UserName, UserEmail = s.Email }).ToList();//匿名类型  
        var select3 = list.Select(s => new UserInfo { UserId = s.Id, UserName = s.UserName, UserEmail = s.Email }).ToList();  
        var select1Linq = (from l in list  
                           select l.Id).ToList();  
        var select2Linq = (from l in list  
                           select new { l.UserName, UserEmail = l.Email }).ToList();  
        var select3Linq = (from l in list  
                           select new UserInfo { UserId = l.Id, UserName = l.UserName, UserEmail = l.Email }).ToList();  
        //SelectMany():查询出指定实体中的指定子集  
        var selectMany = groupJoin.SelectMany(s => s.g).ToList();  
        var country1 = groupJoin.SelectMany(s => s.g).Select(s => s.Country).ToList();  
        var country2 = groupJoin.Select(s => s.g.Select(ss => ss.Country)).ToList();

        //Skip():跳过指定个数,常用于分页等  
        var skip = select1.Skip();  
        //Take():获取指定个数,常用于分页等  
        var take = select1.Take();  
        //SkipWhile():跳过值,直到符合条件为止,按序跳过,当符合条件开始获取剩余的  
        //直译:跳过直到  
        var skipWhile1 = select1.SkipWhile(w => w < ).ToList();  
        var skipWhile2 = select1.SkipWhile(w => w == ).ToList();  
        //TakeWhile():获取值,直到符合条件为止,按序获取,从第一条获取,当不符合条件则跳出  
        //直译:获取直到  
        var takeWhile1 = select1.TakeWhile(w => w < ).ToList();  
        var takeWhile2 = select1.TakeWhile(w => w == ).ToList();

        //Sum():求和,指定值的和,与sql中的功能相同  
        var sum = list.Sum(s => s.Id);  
        //Union():追加数据,与sql中的功能相同  
        var doubleList = select1.Union(skip).ToList();  
        //Where():查询条件,与sql中的功能相同  
        var where = select1.Where(w => w > ).ToList(); ;

        //删除指定数据  
        //Remove():删除指定数据,参数为数据类型  
        //RemoveAt():删除指定索引位置的数据  
        //RemoveRange():批量删除指定索引位置的数据(索引位置,  删除个数)  
        //RemoveAll():删除全部符合条件的数据  
        list.Remove(firstOrDefault);  
        list.RemoveAt();  
        list.RemoveRange(, );  
        list.RemoveAll(r => r.Id > );

        var test = from l in list  
                   join nl in newList on l.Id equals nl.UserId  
                   let x = l.Password  
                   select new { x, nl };

        Console.ReadKey();