.NET 6 中添加了许多 LINQ 方法。 下表中列出的大多数新方法在 System.Linq.Queryable 类型中具有等效方法。
欢迎关注
如果你刻意练习某件事情请超过10000小时,那么你就会达到世界级别
TryGetNonEnumeratedCount
尝试在不强制枚举的情况下确定序列中的元素数。
List<object> numbers1 = new List<object>() { 5, 4, "nihao" };
int num = 0;
numbers1.TryGetNonEnumeratedCount(out num);
num输出为3
Chunk
将序列的元素拆分为指定大小的区块
var list = new List<dynamic>
{
new { Id = 1, Property = "value1" },
new { Id = 2, Property = "value2" },
new { Id = 3, Property = "value1" }
};
var a = list.Chunk(2);
返回 两个元素,第一个list长度为2,第二个为1
ElementAt方法
返回元素指定索引或者结束的索引
var list = new List<dynamic>
{
new { Id = 1, Property = "value1" },
new { Id = 2, Property = "value2" },
new { Id = 3, Property = "value1" },
new { Id = 4, Property = "value4" },
new { Id = 5, Property = "value2" },
new { Id = 6, Property = "value6" },
new { Id = 7, Property = "value7" },
new { Id = 8, Property = "value8" },
new { Id = 9, Property = "value9" }
};
var b=list.ElementAt(2);
var a=list.ElementAt(^2);
a返回的是id=8的item
b返回的是id=9的item
MaxBy 和 MinBy
返回元素中最大值或最小值
- MaxBy 返回元素中的最大元素
- MinBy 返回元素中的最小元素
List<int> numbers1 = new List<int>() { 5, 4, 1, 3, 9, 8, 6, 7, 12, 10 };
var maxnum= numbers1.MaxBy(x => x);
var mixnum= numbers1.MinBy(x => x);
maxnum输出为12,minnum为1
DistinctBy
根据某元素去重
-
(相当于以前的自定义方法)
var list = new List<dynamic>
{
new { Id = 1, Property = "value1" },
new { Id = 2, Property = "value2" },
new { Id = 3, Property = "value1" }
};
// returns objects with Id = 1, 2, but not 3
var distinctList = list.DistinctBy(x => x.Property).ToList();
返回id为1和2的
就相当于自定义扩展方法
public static IEnumerable<t> DistinctBy<t>(this IEnumerable<t> list, Func<t, object> propertySelector)
{
return list.GroupBy(propertySelector).Select(x => x.First());
ExceptBy
返回 两个序列的元素的集合差值的序列
IntersectBy
返回两个序列元素 得交际
UnionBy
连接不同集合,过滤某元素相同项
FirstOrDefault
返回序列中满足条件的第一个元素;如果未找到这样的元素,则返回默认值
LastOrDefault
返回序列中的最后一个元素;如果未找到该元素,则返回默认值
SingleOrDefault
返回序列中的唯一元素;如果该序列为空,则返回默认值;如果该序列包含多个元素,此方法将引发异常。
Take
从序列的开头返回指定数量的相邻元素
int[] grades = { 59, 82, 70, 56, 92, 98, 85 };
IEnumerable<int> topThreeGrades =
grades.OrderByDescending(grade => grade).Take(3);
Console.WriteLine("The top three grades are:");
foreach (int grade in topThreeGrades)
{
Console.WriteLine(grade);
}
/*
This code produces the following output:
The top three grades are:
98
92
85
*/
Zip
将指定函数应用于两个序列的对应元素,以生成结果序列
int[] numbers = { 1, 2, 3, 4 };
string[] words = { "one", "two", "three" };
var numbersAndWords = numbers.Zip(words, (first, second) => first + " " + second);
foreach (var item in numbersAndWords)
Console.WriteLine(item);
// This code produces the following output:
// 1 one
// 2 two
// 3 three
https://www.cnblogs.com/netcore5/p/15707082.html
https://blog.csdn.net/qq_40732336/article/details/122021224