C# LINQ 基础 互动版

在线工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器

join

  在LINQ中同样也可以使用join子句对有关系的数据源或数据对象进行查询,但首先这两个数据源必须要有一定的联系。示例代码如下:

var str = from p in PersonList join car in CarList on p.cid equals car.cid select p;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace linq
{
    class student
    {
       public string name { get; set; }
       public int age { get; set; }
       public int sex { get; set; }
       public int id { get; set; }
    }
    class book
    {
        public string bookname { get; set; }
        public int id { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var items = new List&ltstudent&gt();
            items.AddRange(new student[]
            { new student{name="Tom",age=20,sex=1,id=1},
              new student{name="Jim",age=23,sex=1,id=2},
              new student{name="John",age=24,sex=1,id=3},
              new student{name="Marry",age=22,sex=0,id=4},
              new student{name="Lucy",age=21,sex=0,id=5}
            });

            var books = new List&ltbook&gt();
            books.AddRange(new book[] 
            {
                new book{bookname="C",id=1},
                new book{bookname="C++",id=2},
                new book{bookname="C#",id=3},
                new book{bookname="Word",id=1},
                new book{bookname="Excel",id=1}
            });

            // 连接两个集合,并把查询结果作为新集合
            var data = from a in items 
                       join b in books on a.id equals b.id
                       orderby a.age descending
                       select new {a.id,a.name,a.age,b.bookname }; 

            foreach (var ss in data)
            {
                //输出每个人所拥有的书
                Console.WriteLine(ss.name+" "+ss.bookname); 
            }
        }
    }
}