【问题标题】:How to generate an array from multiples properties of a class如何从类的多个属性生成数组
【发布时间】:2014-07-03 16:35:07
【问题描述】:

有一个简单的模型:

public class SimpleClass
{
    public string prop1 { get; set; }
    public string prop2 { get; set;}
}

还有一个集合:

List<SimpleClass> myCollection = new List<SimpleClass>();

我想做以下事情:

var headerCollection = new List<string>();

foreach(var item in myCollection)
{
    headerCollection.add(item.prop1);
    headerCollection.add("Total");
    headerCollection.add("Date");
    //...
    headerCollection.add(item.prop2);
}

但我需要对对象使用 linq。

我试过了:

var modifiedHeaders = myCollection
    .Select(item => new[] { item.CON_DESCRIPCION, "Total", "Date", item.prop2 });

但它会生成一个类型的集合:List&lt;string[]&gt;。如何解决?

【问题讨论】:

    标签: c# linq linq-to-objects


    【解决方案1】:

    您只需要使用SelectMany 而不是Select

    var mh = myCollection.SelectMany(i =>
        new[] { i.CON_DESCRIPTION, "Total", "Date", i.prop2 });
    

    【讨论】:

      【解决方案2】:

      Select 之后使用SelectMany

      var modifiedHeaders = myCollection
             .Select(item => new[] { item.CON_DESCRIPCION, "Total", "Date", item.prop2 })
             .SelectMany(x => x);
      

      【讨论】:

        【解决方案3】:

        将 Select 更改为 SelectMany:

        var modifiedHeaders = myCollection
            .SelectMany(item => new[] { item.CON_DESCRIPCION, "Total", "Date", item.prop2 });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-07-23
          • 2021-12-20
          • 2020-04-21
          • 1970-01-01
          • 2018-07-12
          相关资源
          最近更新 更多