C# LINQ 基础 互动版

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

Union

Union是将两个集合进行合并操作,过滤相同的项。示例代码为:

var q = ( from c in db.Customers select c.Country ).Union( from e in db.Employeesselect e.Country );
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}
            });
            // 列出所有的id 去掉重复的
            var data = (from a in items select a.id ).Union (from e in books select e.id);
            foreach (var ss in data)
            {
                Console.WriteLine(ss);
            }
        }
    }
}