VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • C#教程之【Linq】常用语法汇总

语言继承查询(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>();
复制代码


相关教程