首页 > 编程语言 >【C#】一个喜欢用Python的菜狗在尝试Linq之后总结的常见用法以及示例

【C#】一个喜欢用Python的菜狗在尝试Linq之后总结的常见用法以及示例

时间:2024-08-30 18:16:02浏览次数:4  
标签:Console 示例 Python CityId C# numbers WriteLine var

1.筛选 (Where)

筛选集合中的元素。
类似python中列表推导式中的if

示例
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 列表推导式中的映射。

示例
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()。

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()。

示例
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()。

示例
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() 和列表推导式。

示例
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()。

示例
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 中的切片操作。

示例
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 中的切片操作。

示例
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 中的集合操作。

示例
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 关键字。

示例
int[] numbers = { 1, 2, 3, 4, 5 };
bool hasThree = numbers.Contains(3);

Console.WriteLine(hasThree);
// 输出:True

python的实现
3 in [1, 2, 3, 4, 5]

标签:Console,示例,Python,CityId,C#,numbers,WriteLine,var
From: https://www.cnblogs.com/asyaB404/p/18389245

相关文章

  • 【信息收集】cms识别
    一、云悉二、潮汐指纹三、CMS指纹识别四、whatcms五、御剑cms识别收集好网站信息之后,应该对网站进行指纹识别,通过识别指纹,确定目标的cms及版本,方便制定下一步的测试计划,可以用公开的poc或自己累积的对应手法等进行正式的渗透测试。一、云悉http://www.yunsee.cn/inf......
  • 2024-08-30 error [email protected]: The engine "node" is incompatible with this m
    删掉依赖,使用yarn重新拉取,保错如下:[email protected]:Theengine"node"isincompatiblewiththismodule.Expectedversion">=18".Got"16.19.1" 错误[email protected]:引擎“节点”与此模块不兼容。预期版本“>=18”。得到“16.19.1”意思就是yarn拉取依赖过程中......
  • CVE2024-4577 成因梳理
    CVE-2012-1823提到PHP-CGI有关的漏洞就不得不提起CVE-2012-1823该漏洞利用php-cgi将用户传入的cgi数据中的query_string部分的-后参数当做了脚本的处理参数处理攻击者可以利用-d参数修改配置项实现远程命令执行的效果也可以-i读出源码当时这个漏洞被apache修复了修复的方......
  • MacOS使用ntfs-3g免费支持NTFS文件系统读写
    下面这个方案是基于Tuxera公司贡献的开源版本ntfs-3g来进行实现,在macos14.5上进行验证;该方案对系统有一定的修改,但是基于开源实现,所以为免费的解决方案。ntfs-3g安装执行以下命令brewtapgromgit/homebrew-fusebrewinstallntfs-3g-mac磁盘挂载如果插入的磁盘已挂载,......
  • PY32F002A单片机开发板 PY32F002AF15P6开发板 32位MCU,M0+内核
    PY32F002A开发板上搭载的是PY32F002AF15P6单片机,TSSOP20封装,开发板使用TypeC接口供电,可以用来对PY32F002A芯片进行开发调试。PY32F002A开发板推荐使用我们的PY32link来下载仿真,绝大部分的STlink,Jlink,DAPlink也可以下载仿真,需自行测试。开发资料齐全,提供了LL库和HAL库,支持IAR......
  • react常用 Hooks
    ReactHooks是React16.8引入的一项功能,它允许你在函数组件中使用状态和其他React特性,而不需要编写类组件。Hooks使函数组件可以管理本地状态、处理副作用、使用上下文等,使得函数组件更加强大和灵活。以下是常用的ReactHooks及其使用方法:useStateimportReact,{us......
  • 使用ClassLoader.getSystemResource更新上线后空指针异常
     目录 问题描述:原问题代码:问题原因以及解决思路:解决方法:问题描述:项目中使用到一个功能,于是在资源路径下加了点依赖包:更新上线后,发现使用ClassLoader.getSystemResource("dependencies")找不到依赖包原问题代码:URLresourceURL=ClassLoader.getSystemResource(......
  • g++链接报错:undefined reference to typeinfo of xxx
    g++链接报错:undefinedreferencetotypeinfoofxxx问题背景在项目中遇到了这样一个问题:C++文件编译都OK,但链接的时候报错:undefinedreferencetotypeinfoforxxx。std::typeinfo是C++中的RTTI(RunTimeTypeIdentification)机制中记录类型信息用的,dynamic_cast和typeid......
  • PyTorch深度学习实战(26)—— PyTorch与Multi-GPU
    当拥有多块GPU时,可以利用分布式计算(DistributedComputation)与并行计算(ParallelComputation)的方式加速网络的训练过程。在这里,分布式是指有多个GPU在多台服务器上,并行指一台服务器上的多个GPU。在工作环境中,使用这两种方式加速模型训练是非常重要的技能。本文将介绍PyTorch中......
  • 【React】React事件和HTML事件的区别
    React写法<buttononClick={handleClick}>测试</button>HTML写法<buttononclick="handleClick()">测试</button>区别ReactHTML原生事件绑定方式小驼峰命名法,事件处理函数通过JSX语法直接绑定全小写形式定义事件处理函数函数引用内联的字符串表达式事件对象基于Ev......