简体   繁体   中英

Linq Select Many from nested list

Given the following code, I'd like to select all "parties" at some position in the array:

var f1 = new Filing();
var f2 = new Filing();
var f3 = new Filing();
var f4 = new Filing();

var p1 = new Party() {Name = "p1"};
var p2 = new Party() { Name = "p2" };
var p3 = new Party() { Name = "p3" };

var p4 = new Party() { Name = "p4" };
var p5 = new Party() { Name = "p5" };
var p6 = new Party() { Name = "p6" };

var p7 = new Party() { Name = "p7" };
var p8 = new Party() { Name = "p8" };
var p9 = new Party() { Name = "p9" };

var p10 = new Party() { Name = "p10" };
var p11 = new Party() { Name = "p11" };
var p12 = new Party() { Name = "p12" };

var p1List = new List<Party>();
p1List.Add(p1);
p1List.Add(p2);
p1List.Add(p3);
f1.Parties = p1List;

var p2List = new List<Party>();
p2List.Add(p4);
p2List.Add(p5);
p2List.Add(p6);
f2.Parties = p2List;

var p3List = new List<Party>();
p3List.Add(p7);
p3List.Add(p8);
p3List.Add(p9);
f3.Parties = p3List;

var p4List = new List<Party>();
p4List.Add(p10);
p4List.Add(p11);
p4List.Add(p12);
f4.Parties = p4List;

var fList = new List<Filing>();

fList.Add(f1);
fList.Add(f2);
fList.Add(f3);
fList.Add(f4);

What I want is to get a list of all Parties in the 0th position for all Filings... example would return p1, p4, p7, and p10. I tried:

fList.SelectMany(f => f.Parties[0]);

...but get a compilation error stating that SelectMany cannot be inferred from the usage. Any ideas?

SelectMany assumes that its argument will return an IEnumerable. Your argument returns a single object; therefore a simple Select is more appropriate than a SelectMany.

Alt1

var yourValues = fList.SelectMany(x => x.Parties.Take(1)).Select(s => s.Name);

Alt2

var yourValues = fList.Select(x => x.Parties.First().Name);

foreach (var val in yourValues)
{
   Console.WriteLine(val); //p1 p4 p7 p10
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM