【问题标题】:List of complex objects to list of named tuples复杂对象列表到命名元组列表
【发布时间】:2020-01-23 01:41:00
【问题描述】:

给定一个List<ComplexObject>,我如何创建一个新的命名元组列表?因此,对于原始列表中的每个 ComplexObject,使用来自 ComplexObject 的某些值创建一个新元组?

public class ComplexObject 
{
    public string SomeString { get; set; }
    public int SomeInt { get; set; }
    public bool SomeBool { get; set; }
    // More properties that are irrelevant for the purpose of this question...
}

这就是我正在尝试的:

List<ComplexObject> complexObjects = new List<ComplexObject>
{
    new ComplexObject { SomeString = "SomeString01", SomeInt = 1, SomeBool = true },
    new ComplexObject { SomeString = "SomeString02", SomeInt = 2, SomeBool = false },
    new ComplexObject { SomeString = "SomeString03", SomeInt = 3, SomeBool = true },
};

List<(string SomeString, int SomeInt, bool SomeBool)> complexTuples 
    = complexObjects.SelectMany(obj => (obj.SomeString, obj.SomeInt, obj.SomeBool));

但是这会导致错误:

无法从用法中推断方法“Enumerable.SelectMany(IEnumerable, Func>)”的类型参数。尝试明确指定类型参数。

【问题讨论】:

    标签: c# linq tuples


    【解决方案1】:

    你快到了,只有两个问题:

    • 您需要使用Select 而不是SelectMany,您只是在执行 1:1 转换
    • 您需要致电ToList 才能获得List&lt;T&gt; 而不是IEnumerable&lt;T&gt;
    List<(string SomeString, int SomeInt, bool SomeBool)> complexTuples =
        complexObjects.Select(obj => (obj.SomeString, obj.SomeInt, obj.SomeBool)).ToList();
    

    【讨论】:

      【解决方案2】:

      好吧,方法SelectMany 将集合集合扁平化为单个集合,因为这里不是这种情况,所以您不需要使用此函数。

      因此,我们将使用.Select。不要忘记.Select 返回IEnumerable&lt;T&gt;,如果我们尝试将其分配给List&lt;T&gt;,它将失败。

      您可以将代码更改为:

      List<(string SomeString, int SomeInt, bool SomeBool)> complexTuples
                      = complexObjects.Select(obj => (obj.SomeString, obj.SomeInt, obj.SomeBool)).ToList();
      

      它现在按预期工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-07
        • 2019-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-04
        • 1970-01-01
        相关资源
        最近更新 更多