gpt4 book ai didi

c# - 带有三元运算符的 IEnumerable Select 语句

转载 作者:行者123 更新时间:2023-11-30 22:01:58 25 4
gpt4 key购买 nike

我在使用 IEnumerable<string> 时有一个奇怪的行为使用三元运算符和 Select声明。
我有两个包含不同对象的列表。一个列表包含 Enums另一个列表包含对象。这些对象确实有一个 String属性(property)。
如果一个列表是 nullempty我想获取另一个列表的值。
这是一些代码:

public class ExportItem
{
public string Type;
...
}

public enum ExportType
{
ExportType1,
ExportType2,
...
}

List<ExportItem>总是由配置文件填充。 List<ExportType>如果提供命令行参数,则填充。所以如果List<ExportType>已填满我想使用它们,否则我想使用配置文件中的那些。
所以我的代码是这样的:

IEnumerable<string> exportTypes = MyListOfExportTypes != null &&
MyListOfExportTypes.Any() ? MyListOfExportTypes.Select(x => x.ToString()) :
MyListOfExportItems.Select(x => x.Type);

问题是exportTypesnull但我不明白...
当我使用 if-else 执行此操作时一切都按预期工作。另外如果 exportTypes类型为 List<string>我调用ToList()Select之后声明一切正常。
使用 var a = MyListOfExportTypes.Select(x => x.ToString());var b = MyListOfExportItems.Select(x => x.Type);确实按预期工作。
必须是三元运算符和/或 IEnumerable 的东西.但是什么?

或者我错过了什么?有什么建议么?

编辑:
我现在有一个截图... enter image description here

注意上面的代码foreach尽管如此……

最佳答案

不确定是否有人回答,但我认为这与您使用的是 LINQ 延迟执行有关。

编写 LINQ 查询时,创建查询和执行查询之间存在差异。

编写 select 语句,就是创建查询,添加 ToList() 来执行它。把它想象成在 SQL 服务器控制台中编写 SQL 查询(这是编写阶段),一旦你按下 F5(或播放按钮),你就会执行它。

我希望这个小代码示例有助于阐明它。

    public class SomeClass
{
public int X { get; set; }
public int Y { get; set; }

public void Test()
{
//Here I'm creating a List of Some class
var someClassItems = new List<SomeClass> {
new SomeClass { X = 1, Y = 1 },
new SomeClass { X = 2, Y = 2 }
};

//Here I'm creating a Query
//BUT, I'm not executing it, so the query variable, is represented by the IEnumerable object
//and refers to an in memory query
var query = someClassItems.
Select(o => o.X);

//Only once the below code is reached, the query is executed.
//Put a breakpoint in the query, click the mouse cursor inside the select parenthesis and hit F9
//You'll see the breakpoint is hit after this line.
var result = query.
ToList();

}
}

关于c# - 带有三元运算符的 IEnumerable Select 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27275098/

25 4 0