当前位置:网站首页>C# Linq Demo

C# Linq Demo

2022-07-05 23:18:00 ou. cs

List of articles

select

Assign values to new types

  List<Students> studentsSource = new List<Students>()
        {
    
            new Students()
            {
    
                Id= 1,
                Name="11",
                ClassId=1,
                Age=25,
            },
              new Students()
            {
    
                Id= 2,
                Name="22",
                ClassId=2,
                Age=22,
            },

               new Students()
            {
    
                Id= 3,
                Name="33",
                ClassId=1,
                Age=33,
            },

               new Students()
            {
    
                Id= 4,
                Name="44",
                ClassId=2,
                Age=21,
            },

                new Students()
            {
    
                Id= 5,
                Name="55",
                ClassId=5,
                Age=55,
            },

        };
 var query =studentsSource.Select(x => new {
    id=x.Id,age=x.Age>50?999:0});

            foreach (var item in query)
            {
    
                Console.WriteLine(item.id);

                Console.WriteLine(item.age);
   
                Console.WriteLine("\n");
            }

join

            List<StuClass> stuClasses = new List<StuClass>()
            {
    
                new StuClass{
    Id=1,ClassName="11"},
                new StuClass{
    Id=2,ClassName="22"},
                new StuClass{
    Id=3,ClassName="33"},
                new StuClass{
    Id=4,ClassName="44"},
            };

            // ==  Change it into equals
            {
    
                var query2 = from s in studentsSource
                            join c in stuClasses on s.ClassId equals c.Id
                            select new StuAndClass {
    
                            Id=s.Id,
                            ClassId=s.ClassId,
                            Age=s.Age,
                            ClassName=c.ClassName,

                            };

                var query3 = studentsSource.Join(stuClasses, s => s.ClassId, c => c.Id, (s, c) => new StuAndClass
                {
    
                    Id = s.Id,
                    ClassId = s.ClassId,
                    Age = s.Age,
                    ClassName = c.ClassName,

                });
            }

other

                // Get the first data 
                //var query3 = studentsSource.Take(2);
                //var query4 = studentsSource.Skip(2);
                //var query5 = studentsSource.OrderBy(s=>s.Name);
                var query2 = studentsSource.Select(s => s.Name);
                var query6 = studentsSource.Where(s=>s.Name.Contains("1"));
原网站

版权声明
本文为[ou. cs]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140333425644.html