欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

【Linq】常用语法汇总

程序员文章站 2022-09-25 12:18:46
语言继承查询(Language Integrated Query, LINQ),在C#编程语言中集成了查询语法,可以用相同的语法访问不同的数据源,LINQ提供了不同数据源的抽象层,所以可以使用相同语法。 1、条件查询(Where) 需要注意的是,延迟查询 解决这个问题,只需要用 ToList(); ......

语言继承查询(Language Integrated Query, LINQ),在C#编程语言中集成了查询语法,可以用相同的语法访问不同的数据源,LINQ提供了不同数据源的抽象层,所以可以使用相同语法。

public class Book
{
    public int Id { get; set; }
    /// <summary>
    /// 书名
    /// </summary>
    public string BookName { get; set; }
    /// <summary>
    /// 作者id
    /// </summary>
    public int AutherId { get; set; }
    /// <summary>
    /// 类型
    /// </summary>
    public string Type { get; set; }
    /// <summary>
    /// 售价
    /// </summary>
    public decimal Price { get; set; }
    /// <summary>
    /// 销量
    /// </summary>
    public int Sales { get; set; }
}
public class Auther
{
    public int Id { get; set; }
    /// <summary>
    /// 作者
    /// </summary>
    public string AutherName { get; set; }
}
public class Library
{
    public string Address { get; set; }
    /// <summary>
    /// 书本
    /// </summary>
    public List<Book> BookList { get; set; }
}

1、条件查询(Where)

 var query = from book in bookList
             where book.Price > 50
             orderby book.Sales descending,book.BookName
             select book;
//等同于
var query = bookList.Where(n => n.Price > 50).OrderByDescending(g => g.Sales).ThenBy(y => y.BookName);

  需要注意的是,延迟查询

var ary = new List<string>(){ "Aa", "Bb", "Cc"};

var a1 = ary.Where(n => n.Contains("a"));//["Aa"]

ary.Add("Ga");

a1;//["Aa", "Ga"]

  解决这个问题,只需要用 ToList();

var ary = new List<string>(){ "Aa", "Bb", "Cc"};

var a1 = ary.Where(n => n.Contains("a")).ToList();//["Aa"]

ary.Add("Ga");

a1;//["Aa"]

  索引筛选

//销量大于50且为奇数行
var query = bookList.Where((n, index) => n.Sales > 50 && index%2 != 0);

2、复合查询(SelectMany)

//查找所有图书馆中的小说
var query = from library in libraryList
            from book in library.BookList
            where book.Type == "小说"
            select book;

//等同于
query = libraryList.SelectMany(n => n.BookList).Where(g => g.Type == "小说");

//组织返回结果
query = libraryList.SelectMany(n => n.BookList,  (n, g) => new {n.Address, g.BookName, g.Sales}).Where(y => y.Sales > 100);

3、集合连接

//内连接
var query1 = from book in bookList
         join auther in autherList on book.AutherId equals auther.Id
         select new { book.BookName, auther.AutherName };
//组连接
var query2 = from auther in autherList
           join book in bookList on auther.Id equals book.AutherId into items
           select new { auther.AutherName, Books = items };
//左外连接
var query3 = from book in bookList
            join auther in autherList on book.AutherId equals auther.Id into items
            from auther in items.DefaultIfEmpty()
            select new
            {
                book.BookName,
                AutherName = auther == default(Auther) ? "无" : auther.AutherName
            };
//多条件连接
var query4 = from book in bookList
    join auther in autherList on new {name = book.BookName, id = book.AutherId} equals new {name = auther.AutherName, id = auther.Id}
    select book;

4、排序(OrderBy、ThenBy)

var query = from book in bookList
                orderby book.Sales descending, book.AutherId, book.Price descending 
                select book;
//等同于
query = bookList.OrderByDescending(n => n.Sales).ThenBy(g => g.AutherId).ThenByDescending(y => y.Price);

5、分组(GroupBy)

//单一条件分组
var query = from book in bookList
                        group book by book.Type into bs
                        select bs.First();
//等同于
query = bookList.GroupBy(n => n.Type).Select(g => g.First());

//多条件分组
var query = from book in bookList
            group book by new { book.Type, book.AutherId } into bs
            select new
            {
                Type = bs.First().Type,
                AutherId = bs.First().AutherId,
                Count = bs.Count()
            };
//等同于
query = bookList.GroupBy(n => new {n.Type, n.AutherId}).Select(g => new
            {
                Type = g.First().Type,
                AutherId = g.First().AutherId,
                Count = g.Count()
            });

6、合并与分区(Zip、Take、Skip)

int[] numbers = { 1, 2, 3 };
string[] words = { "One", "Two", "Three", "Four" };
//元素依次组合,长度为较小的集合
IEnumerable<string> zip = numbers.Zip(words, (n, g) => n + "=" + g);//["1=One", "2=Two", "3=Three"]

//跳过集合的前n个元素
var skip = words.Skip(3);//["Four"]
//获取集合的前n个元素,有延迟
var take = numbers.Take(2);//[1, 2]

int pageSize = 3;//每页容量
int pageNum = 0;//页数
var page = words.Skip(pageSize * pageNum).Take(pageSize);//["One", "Two", "Three"]

7、集合操作(Distinct、Union、Concat、Intersect、Except)

int[] ary1 = {1, 2, 2, 4, 5};
int[] ary2 = {3, 5, 5, 6, 10, 7};

//合并,自动去重
var union = ary1.Union(ary2);//1, 2, 3, 4, 5, 6, 7, 10
//合并,不会去重
var concat = ary1.Concat(ary2);//1, 2, 2, 4, 5, 3, 5, 5, 6, 10, 7
//去重
var distict = ary1.Distinct();//1, 2, 4, 5
//取交集,自动去重
var intersect = ary1.Intersect(ary2);//5
//取补集,自动去重
var except = ary1.Except(ary2);//1, 2, 4

8、类型筛选(ofType)

object[] data = { "one", 1 , 2 ,"three"};
var query = data.ofType<string>();

9、聚合操作符(Count、Sum、Min、Max、Average、Aggregate)

//个数
var count = bookList.Count(n => n.Sales > 50);
//求和
var sum = bookList.Sum(n => n.Price);
//最小值
var min = bookList.Min(n => n.Sales);
//最大值
var max = bookList.Max(n => n.Price);
//平均值
var average = bookList.Average(n => n.Sales);
//累加,总销量
var aggregate1 = bookList.Select(n => n.Sales).Aggregate((g, y) => g + y);
//累加,初始值
var aggregate2 = bookList.Select(n => n.Sales).Aggregate(10, (g, y) => g + y);
//累加,初始值,结果处理
var aggregate3 = bookList.Select(n => n.Sales).Aggregate(10, (g, y) => g + y, result => result/100);

10、转换操作符 (ToArray、ToDictionary、ToList、ToLookup、Cast)

Book[] ary = bookList.ToArray();

List<Book> list = bookList.ToList();

Dictionary<int, Book> dic = bookList.ToDictionary<Book, int>(n => n.Id);

//转换成LookUp集合,key-以key分组的内部集合
ILookup<string, Book> look = bookList.ToLookup(n => n.Type);

IEnumerable<Book> cast = ary.Cast<Book>();