【问题标题】:Convert List<int?> to List<int> [duplicate]将 List<int?> 转换为 List<int> [重复]
【发布时间】:2015-01-29 11:59:59
【问题描述】:

假设,我有一个 Nullable Integer's 列表,我想将此列表转换为仅包含值的 List&lt;int&gt;

你能帮我解决这个问题吗?

【问题讨论】:

    标签: c# int nullable


    【解决方案1】:

    过滤掉null 值,使用Value 属性获取数字并使用ToList 将它们放入列表中:

    yourList.Where(x => x != null).Select(x => x.Value).ToList();
    

    你也可以使用Cast

    yourList.Where(x => x != null).Cast<int>().ToList();
    

    【讨论】:

    • 如果。我想使用Cast&lt;int&gt;() 将列表中名为UserId 的所有属性转换为整数列表可能吗?
    【解决方案2】:

    你试过了吗:

    List<int> newList = originalList.Where(v => v != null)
                                    .Select(v => v.Value)
                                    .ToList();
    

    ?

    【讨论】:

      【解决方案3】:

      试试:

       var numbers1 = new List<int?>() { 1, 2, null};
       var numbers2 = numbers1.Where(n => n.HasValue).Select(n => n.Value).ToList();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-01
        • 2019-07-28
        • 1970-01-01
        • 2018-04-28
        • 2016-12-26
        • 1970-01-01
        相关资源
        最近更新 更多