gpt4 book ai didi

c# - 使用 LINQ 创建一个包含不同类型的列表?

转载 作者:太空宇宙 更新时间:2023-11-03 23:18:35 24 4
gpt4 key购买 nike

我不想编写一个 4 行循环,而是想使用 LINQ 创建一个新的 List(实际上是一个 IEnumerable)。我知道我可以向 LINQ 提供 lambda 表达式,它会使用该表达式映射列表的元素,但它会更改 List 包含的类型吗?

// My List of objects
List<MyDBDocType> myDBDocs = ...;
// How they are mapped
BsonDocument myDBDocAsBson = myDBDocs[0].ToBsonDocument();
// Function signature that takes a List that holds a separate type
MyDocCollection.InsertManyAsync([IEnumerable<BsonDocument> documents], ...);

最佳答案

LINQ 有一些方法,有些会改变数据类型,有些则不会。

例如,Select 子句可以改变数据类型:

//suppose your MyDBDocType has property called MyInt with data type: int
var result = myDBDocs.Select(x => x.MyInt); //this will result in IEnumerable<int>

但是Where方法保留了数据类型,它只是根据lambda表达式过滤结果:

var result = myDBDocs.Select(x => x.MyInt > 3); //this will result in IEnumerable<MyDBDocType>

其他 LINQ 方法,例如 FirstLastFirstOrDefaultExceptIntersectDistinctSkipSkipWhile 等...也不要更改数据类型。但是像 SelectSelectMany 这样的方法改变了数据类型。

在您的情况下,如果您只想过滤原始查询中的某些结果而不更改数据类型,请考虑使用 Where

关于c# - 使用 LINQ 创建一个包含不同类型的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36315122/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com