【问题标题】:IEnumerable Select statement with ternary operator带有三元运算符的 IEnumerable Select 语句
【发布时间】:2014-12-03 15:09:10
【问题描述】:

我使用带有三元运算符的IEnumerable<string>Select 语句有一个奇怪的行为。
我有两个包含不同对象的列表。一个列表包含Enums,另一个列表包含对象。这些对象确实具有String 属性。
如果一个列表是 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 执行此操作时,一切都按预期工作。此外,如果exportTypesList&lt;string&gt; 类型,我在Select 语句之后调用ToList(),一切正常。
使用 var a = MyListOfExportTypes.Select(x =&gt; x.ToString());var b = MyListOfExportItems.Select(x =&gt; x.Type); 确实可以按预期工作。
必须是三元运算符和/或IEnumerable。但是什么?

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

编辑:
我现在有截图...

请注意,foreach 上面的代码仍然有效...

【问题讨论】:

  • 你怎么知道 exportTypes 为空?
  • 通过调试代码。
  • 如果你打电话给exportTypes.ToList,你会得到 NullReferenceException 吗?
  • 它对我来说绝对没问题。你确定MyListOfExportTypesMyListOfExportItems 都不为空吗?实际上,这可能会产生不同的问题。
  • @Selman22 所以这真的很奇怪。不,我没有!在执行Select 语句并将鼠标悬停在exportTypes 上之后,调试器会显示null,但我可以调用ToList(),一切都按预期进行。某种 VS 2010 的错误?

标签: c# linq ienumerable ternary-operator


【解决方案1】:

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

在编写 LINQ 查询时, 创建查询和执行查询是有区别的。

编写选择语句,创建查询,添加 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();

        }
    }

【讨论】:

    猜你喜欢
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-13
    • 2015-10-13
    • 2016-04-25
    • 2016-06-28
    相关资源
    最近更新 更多