【C#】一个喜欢用Python的菜狗在尝试Linq之后总结的常见用法以及示例
下面的每个代码示例都包含对应的python实现
方便从python转C#的人更好的理解其实现
1.拓展方法
1.筛选 (Where)
筛选集合中的元素。
类似python中列表推导式中的if
public static IEnumerable<TSource> Where<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate );
参数解释:
source: 要筛选的集合。
predicate: 一个委托,定义筛选条件。返回 true 的元素将被包含在结果中。
示例
int[] numbers = { 1, 2, 3, 4, 5, 6 }; var evenNumbers = numbers.Where(n => n % 2 == 0); foreach (var num in evenNumbers) { Console.WriteLine(num); } // 输出:2, 4, 6 python中的实现 [ i for i in range(0,99) if i % 2 == 0]
2.投影 (Select)
将集合中的元素映射到新的形式
类似于 Python 列表推导式中的映射。
public static IEnumerable<TResult> Select<TSource, TResult>( this IEnumerable<TSource> source, Func<TSource, TResult> selector );
参数解释:
source: 要进行投影的集合。
selector: 一个委托,用于定义如何将每个元素转换为新的形式。
示例
string[] words = { "apple", "banana", "cherry" }; var wordLengths = words.Select(w => w.Length); foreach (var length in wordLengths) { Console.WriteLine(length); } // 输出:5, 6, 6 python中的实现 [len(word) for word in ["apple", "banana", "cherry"]]
3.排序 (OrderBy, OrderByDescending)
对集合进行升序或降序排序
类似于 Python 中的 sorted()。
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector );
public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector );
参数解释:
source: 要排序的集合。
keySelector: 一个委托,定义用于排序的键值。
OrderBy示例
//仅演示OrderBy,OrderByDescending同理 string[] names = { "Charlie", "Alice", "Bob" }; var sortedNames = names.OrderBy(name => name); foreach (var name in sortedNames) { Console.WriteLine(name); } // 输出:Alice, Bob, Charlie python中的实现 sorted(["Charlie", "Alice", "Bob"])
4.聚合 (Aggregate)
通过指定的函数将集合中的元素合并。
类似于 Python 中的 functools.reduce()。
public static TAccumulate Aggregate<TSource, TAccumulate>( this IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func );
public static TSource Aggregate<TSource>( this IEnumerable<TSource> source, Func<TSource, TSource, TSource> func );
参数解释:
source: 要聚合的集合。
seed: 聚合操作的初始值(仅在第一个重载中使用)。
func: 一个委托,定义如何将每个元素合并到结果中。
示例
int[] numbers = { 1, 2, 3, 4, 5 }; int sum = numbers.Aggregate((total, next) => total + next); Console.WriteLine(sum); // 输出:15 python的实现 from functools import reduce reduce(lambda total, next: total + next, [1, 2, 3, 4, 5])
5.分组 (GroupBy)
将集合按某个条件分组。 类似于 Python 中使用 itertools.groupby()。
public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector );
public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector );
参数解释:
source: 要分组的集合。
keySelector: 一个委托,定义分组键。
elementSelector: 一个委托,定义每个元素在分组中的形式(第二个重载使用)。
示例
string[] words = { "apple", "banana", "cherry", "avocado" }; var groupedWords = words.GroupBy(w => w[0]); foreach (var group in groupedWords) { Console.WriteLine($"Key: {group.Key}"); foreach (var word in group) { Console.WriteLine(word); } } // 输出: // Key: a // apple // avocado // Key: b // banana // Key: c // cherry python的实现 from itertools import groupby words = ["apple", "banana", "cherry", "avocado"] grouped_words = {k: list(v) for k, v in groupby(sorted(words), key=lambda w: w[0])}
6.连接 (Join)
连接两个集合,并返回匹配的元素。 类似于 Python 中使用 zip() 和列表推导式。
public static IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>( this IEnumerable<TOuter> outer, IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, TInner, TResult> resultSelector );
参数解释:
outer: 外部集合(即左集合)。
inner: 内部集合(即右集合)。
outerKeySelector: 一个委托,定义外部集合的键。
innerKeySelector: 一个委托,定义内部集合的键。
resultSelector: 一个委托,定义如何将匹配的元素组合成结果。
示例
var people = new[] { new { Name = "John", CityId = 1 }, new { Name = "Jane", CityId = 2 }, new { Name = "Jake", CityId = 1 } }; var cities = new[] { new { CityId = 1, CityName = "New York" }, new { CityId = 2, CityName = "Los Angeles" } }; var peopleInCities = people.Join( cities, person => person.CityId, city => city.CityId, (person, city) => new { person.Name, city.CityName } ); foreach (var personInCity in peopleInCities) { Console.WriteLine($"{personInCity.Name} lives in {personInCity.CityName}"); } // 输出: // John lives in New York // Jake lives in New York // Jane lives in Los Angeles python的实现 people = [ {"Name": "John", "CityId": 1}, {"Name": "Jane", "CityId": 2}, {"Name": "Jake", "CityId": 1} ] cities = [ {"CityId": 1, "CityName": "New York"}, {"CityId": 2, "CityName": "Los Angeles"} ] people_in_cities = [ {**person, **city} for person in people for city in cities if person["CityId"] == city["CityId"] ]
7.去重 (Distinct)
移除集合中的重复元素。 类似于 Python 中的 set()。
public static IEnumerable
this IEnumerable
);
参数解释:
source: 要去重的集合。
示例
int[] numbers = { 1, 2, 2, 3, 3, 3, 4 }; var distinctNumbers = numbers.Distinct(); foreach (var num in distinctNumbers) { Console.WriteLine(num); } // 输出:1, 2, 3, 4 python的实现 list(set([1, 2, 2, 3, 3, 3, 4]))
8.获取集合的前几个元素 (Take)
获取集合中的前 N 个元素。 类似于 Python 中的切片操作。
public static IEnumerable<TSource> Take<TSource>( this IEnumerable<TSource> source, int count );
参数解释:
source: 要获取元素的集合。
count: 要获取的元素数量。
示例
int[] numbers = { 1, 2, 3, 4, 5 }; var firstThree = numbers.Take(3); foreach (var num in firstThree) { Console.WriteLine(num); } // 输出:1, 2, 3 python [1, 2, 3, 4, 5][:3]
9.跳过集合的前几个元素 (Skip)
跳过集合中的前 N 个元素。 类似于 Python 中的切片操作。
public static IEnumerable<TSource> Skip<TSource>( this IEnumerable<TSource> source, int count );
参数解释:
source: 要跳过元素的集合。
count: 要跳过的元素数量。
示例
int[] numbers = { 1, 2, 3, 4, 5 }; var allButFirstTwo = numbers.Skip(2); foreach (var num in allButFirstTwo) { Console.WriteLine(num); } // 输出:3, 4, 5 python的实现 [1, 2, 3, 4, 5][2:]
10.合并两个集合 (Union)
将两个集合合并,并移除重复项。 类似于 Python 中的集合操作。
public static IEnumerable<TSource> Union<TSource>( this IEnumerable<TSource> first, IEnumerable<TSource> second );
参数解释:
first: 第一个集合。
second: 要合并的第二个集合。
示例
int[] numbers1 = { 1, 2, 3 }; int[] numbers2 = { 3, 4, 5 }; var union = numbers1.Union(numbers2); foreach (var num in union) { Console.WriteLine(num); } // 输出:1, 2, 3, 4, 5 python的实现 set([1, 2, 3]).union([3, 4, 5])
11.检查是否包含元素 (Contains)
检查集合中是否包含指定元素。 类似于 Python 中的 in 关键字。
public static bool Contains<TSource>( this IEnumerable<TSource> source, TSource value );
参数解释:
source: 要检查的集合。
value: 要查找的元素。
示例
int[] numbers = { 1, 2, 3, 4, 5 }; bool hasThree = numbers.Contains(3); Console.WriteLine(hasThree); // 输出:True python的实现 3 in [1, 2, 3, 4, 5]
2.静态方法
1.生成连续整数序列(Range)
生成一个包含一系列连续整数的集合。
public static IEnumerable<int> Range( int start, int count );
参数解释:
start: 序列中第一个整数的值。
count: 要生成的整数的数量。
示例
var range = Enumerable.Range(1, 5); foreach (var num in range) { Console.WriteLine(num); } // 输出:1, 2, 3, 4, 5
在 Python 中的类似实现:
range(1, 6)
2.重复元素(Repeat)
生成一个包含重复元素的序列。
public static IEnumerable<TSource> Repeat<TSource>( TSource element, int count );
参数解释:
element: 要重复的元素。
count: 元素重复的次数。
示例
var repeated = Enumerable.Repeat("Hello", 3); foreach (var item in repeated) { Console.WriteLine(item); } // 输出:Hello, Hello, Hello
在Python中的类似实现
["值类型的对象"] * 3 ["引用类型的对象" for _ in range(3)]
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具