如何从对象列表中获取多个属性到数组?

时间:2016-05-30 10:38:33

标签: c# linq

是否有LINQ状态来传输类似

的类的List
private class ToSelectMany
{
  public string SelectMe1 { get; set; }
  public string SelectMe2 { get; set; }
  public string IgnoreMeString { get; set; }
  public bool IgnoreMeBool { get; set; }
}

到像

这样的数组
[0] "list element 1 - SelectMe1"
[1] "list element 1 - SelectMe2"
[2] "list element 2 - SelectMe1"
[3] "list element 2 - SelectMe2"
[4] "list element 3 - SelectMe1"
[5] "list element 3 - SelectMe2"
...

我试过

List<ToSelectMany> elements = GetElements();
string[] elementArray = elements.SelectMany(a => a.ToSelect1, b => b.ToSelect2);

和一些类似的事情,但它不会起作用。

2 个答案:

答案 0 :(得分:2)

你需要构建一个两个字符串 foreach元素的数组,然后使用SelectMany来连接它们:

string[] elementArray = elements.Select(
     (a, i) => new string[] { 
                 "list elment " + (i + 1) + " - " + a.SelectMe1, 
                 "list elment " + (i + 1) + " - " + a.SelectMe2
     }).SelectMany(x => x).ToArray();

或更好看的c#6版本:

string[] elementArray = elements.Select(
     (a, i) => new string[] { 
                 $"list elment {i+1} - {a.SelectMe1}", 
                 $"list elment {i+1} - {a.SelectMe2}"
     }).SelectMany(x => x).ToArray();

答案 1 :(得分:0)

var i = 0;
var list = new List<string>();
elements.ForEach(p=>{
    i++;
    list.Add("list element " + i + " - " + p.SelectMe1);
    list.Add(("list element " + i + " - " + p.SelectMe2);
});