我无法将多个数组聚合成一个“大数组”,我认为这应该可以在Linq中实现,但我无法理解它:(
考虑一些返回某些dummyObjects数组的方法
public class DummyObjectReceiver
{
public DummyObject[] GetDummyObjects { -snip- }
}
现在某处我有这个:
public class Temp
{
public List<DummyObjectReceiver> { get; set; }
public DummyObject[] GetAllDummyObjects ()
{
//here's where I'm struggling (in linq) - no problem doing it using foreach'es... ;)
}
}
希望我有点清楚我想要实现的目标 (另外我想通过DummyObject有一个int值来命令这个数组......但是orderby应该没问题,...我希望;)
答案 0 :(得分:15)
使用SelectMany
方法将数组返回对象列表展平为数组。
public class DummyObject {
public string Name;
public int Value;
}
public class DummyObjectReceiver {
public DummyObject[] GetDummyObjects() {
return new DummyObject[] {
new DummyObject() { Name = "a", Value = 1 },
new DummyObject() { Name = "b", Value = 2 }
};
}
}
public class Temp {
public List<DummyObjectReceiver> Receivers { get; set; }
public DummyObject[] GetAllDummyObjects() {
return Receivers.SelectMany(r => r.GetDummyObjects()).OrderBy(d => d.Value).ToArray();
}
}
示例:
Temp temp = new Temp();
temp.Receivers = new List<DummyObjectReceiver>();
temp.Receivers.Add(new DummyObjectReceiver());
temp.Receivers.Add(new DummyObjectReceiver());
temp.Receivers.Add(new DummyObjectReceiver());
DummyObject[] result = temp.GetAllDummyObjects();