美文网首页编程中国C#.NET
LINQ表达式用法整理

LINQ表达式用法整理

作者: 小明yz | 来源:发表于2017-07-05 08:44 被阅读168次

收集一些Linq表达式中的一些比较常用的写法,希望能给大家工作当中带来一些便利。

1. Where子句条件过滤结果集型(集合数据使用这种,譬如数组、列表数据,同样适用于Datatable等多列数据集)

类SQL语句的写法,对集合进行运算;

int[] factorsOf300 = { 2, 2, 3, 5, 5 };

var filters = from p in factorsOf300 where p<5 select p;

foreach (var filter in filters)

{

Console.WriteLine("Value: " + Convert.ToString(filter));

}

2. 对数据集进行函数运算型(特别注意select方法里面需要用new关键字来确定记录子集合)

string[] words = { "aPPLE", "BlUeBeRrY", "cHeRry" };

var upperLowerWords = from w in words

select new { Upper = w.ToUpper(), Lower = w.ToLower() };

foreach (var ul in upperLowerWords)

{

Console.WriteLine("Uppercase: {0}, Lowercase: {1}", ul.Upper, ul.Lower);

}

3. 多个数据子集进行复合计算:

int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };

int[] numbersB = { 1, 3, 5, 7, 8 };

var pairs = from a in numbersA

from b in numbersB

where a < b

select new { a, b };

Console.WriteLine("Pairs where a < b:");

foreach (var pair in pairs)

{

Console.WriteLine("{0} is less than {1}", pair.a, pair.b);

}

4. 子集运算,其中常见的算符有 Take, Skip, TakeWhile, SkipWhile.

int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

var first3Numbers = numbers.Take(3);

Console.WriteLine("First 3 numbers:");

foreach (var n in first3Numbers)

{

Console.WriteLine(n);

}

5. 排序运算,

double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 };

var sortedDoubles = from d in doubles

orderby d descending select d;

Console.WriteLine("The doubles from highest to lowest:");

foreach (var d in sortedDoubles)

{

Console.WriteLine(d);

}

6. 分组运算

string[] words = { "blueberry", "chimpanzee", "abacus", "banana", "apple", "cheese" };

var wordGroups = from w in words

group w by w[0] into g

select new { FirstLetter = g.Key, Words = g };

foreach (var g in wordGroups)

{

Console.WriteLine("Words that start with the letter '{0}':", g.FirstLetter);

foreach (var w in g.Words)

{

Console.WriteLine(w);

}

}

7. 集合运算,算符包括Distinct, Union, Intersect, Except。

int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };

int[] numbersB = { 1, 3, 5, 7, 8 };

var uniqueNumbers = numbersA.Union(numbersB);

Console.WriteLine("Unique numbers from both arrays:");

foreach (var n in uniqueNumbers)

{

Console.WriteLine(n);

}

此集合输出为进行整合过后的一个数据集;

8. 转换操作,主要是包含 ToArray, ToList, ToDictionary, OfType这几个操作指令。

double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 };

var sortedDoubles = from d in doubles

orderby d descending

select d;

var doublesArray = sortedDoubles.ToArray();

Console.WriteLine("Every other double from highest to lowest:");

for (int d = 0; d < doublesArray.Length; d += 2)

{

Console.WriteLine(doublesArray[d]);

}

9. 元素操作:

-- First - Simple

-- First - Condition

-- FirstOrDefault - Simple

-- FirstOrDefault - Condition

-- ElementAt

string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };

string startsWithO = strings.First(s => s[0] == 'o');

10. 子序列生成功能:

Range功能:

var numbers = from n in Enumerable.Range(100, 50)

select new { Number = n, OddEven = n % 2 == 1 ? "odd" : "even" };

foreach (var n in numbers)

{

Console.WriteLine("The number {0} is {1}.", n.Number, n.OddEven);

}

Repeat功能:

var numbers = Enumerable.Repeat(7, 10);

foreach (var n in numbers)

{

Console.WriteLine(n);

}

11.集合筛选判断功能:

-- Any - Simple

-- Any - Grouped

-- All - Simple

-- All - Grouped

- Any - Simple

string[] words = { "believe", "relief", "receipt", "field" };

bool iAfterE = words.Any(w => w.Contains("ei"));

-- Any - Grouped功能:

List products = GetProductList();

var productGroups =

from p in products

group p by p.Category into g

where g.Any(p => p.UnitsInStock == 0)

select new { Category = g.Key, Products = g };

12.数据集的聚合功能: Count, Sum, Min, Max, Average, Aggregate函数

int[] factorsOf300 = { 2, 2, 3, 5, 5 };

int uniqueFactors = factorsOf300.Distinct().Count();

13.集合叠加以及顺序比较功能: Concat,EqualAll函数

int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };

int[] numbersB = { 1, 3, 5, 7, 8 };

var allNumbers = numbersA.Concat(numbersB);

14.自定义函数功能:

int[] vectorA = { 0, 2, 4, 5, 6 };

int[] vectorB = { 1, 3, 5, 7, 8 };

int dotProduct = vectorA.Combine(vectorB, (a, b) => a * b).Sum();

Console.WriteLine("Dot product: {0}", dotProduct);

15. Query的使用:Deferred Execution、Immediate Execution、Query Reuse。

int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

int i = 0;

var q = from n in numbers select ++n;

foreach (var v in q)

{

Console.WriteLine("v = {0}, i = {1}", v, ++i);

}

16. 集合连接运算: Cross Join、Group Join、Cross Join with Group Join、Left Outer Join。

string[] productsPrefix = new string[]{

"B",

"D",

"V",

"D",

"R"

};

string[] categories = new string[]{

"Beverages",

"Condiments",

"Vegetables",

"Dairy Products",

"Seafood" };

var q =

from p in productsPrefix

join c in categories on p equals c.Substring(0, 1)

select new { p, Category = c};

foreach (var v in q)

{

Console.WriteLine(v.p + ": " + v.Category);

}

欢迎关注我的公众号(同步更新文章):DoNet技术分享平台

阅读原文

相关文章

  • LINQ表达式用法整理

    收集一些Linq表达式中的一些比较常用的写法,希望能给大家工作当中带来一些便利。 1. Where子句条件过滤结果...

  • Linq

    Linq查询的基本用法和介绍(m为集合中每个元素的别名) Linq的Lambda表达式(因为委托是一个参数,所以可...

  • (转)Linq表达式、Lambda表达式你更喜欢哪个?

    什么是Linq表达式?什么是Lambda表达式? 如图: 由此可见Linq表达式和Lambda表达式并没有什么可比...

  • (转).NET面试题系列[14] - LINQ to SQL与I

    LINQ to Object和LINQ to SQL有何区别? LINQ to SQL可以将查询表达式转换为SQL...

  • Linq用法笔记

    一、什么是Linq? LINQ即Language Integrated Query(语言集成查询),LINQ是集成...

  • ASP.NET LINQ 简介

    目录### 1. 什么是LINQ 2. 扩展方法3. Lambda 表达式4. LINQ查询的两种语法 1. 什么...

  • Language Integrated Query(LINQ,语

    第一次接触到Linq很开心 Linq 有两种写法,一种是 语句,另一种是^表达式 linq用来遍历集合很方便,和f...

  • Java 8 中的 Streams API 详解

    Java 8 中的 Streams API 详解Stream就相当于C#中的linq表达式,lambda表达式语法...

  • Linq的用法总结

    一.linq的适用类型 二.linq的好处方便我们对保存的数据进行筛选,把数据保存为自己想要的排序,或者快速筛选出...

  • Java 8|Stream 高级用法

    前面几篇文章简单介绍了 Stream 的用法,今天整理一下部分高级用法。 方法引用 Lambda 表达式经常会有如...

网友评论

  • 金戈大王:请按照简书MarkDown格式排版,把代码放到代码块里,谢谢~
    金戈大王: @小明yz
    ```
    代码写在这里
    ```
    小明yz:@金戈大王 不太会用啊

本文标题:LINQ表达式用法整理

本文链接:https://www.haomeiwen.com/subject/urmfhxtx.html