I have this list:
Annie – P
May – ” ”
Annie – P
May – P
And I want to get the last element based on the names:
Annie – P
May – P
I have this code but it’s either throwing an error: The type arguments for method 'System.Linq.Enumerable.SelectMany<TSource,TResult>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,System.Collections.Generic.IEnumerable<TResult>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. or I only get the very last element in the list (May – P).
class Passenger
{
public string Name { get; set; }
public int PassengerID { get; set; }
public List<TravelDoc> TravelDocs { get; set; }
}
class TravelDoc
{
public string DocType { get; set; }
public int? DocNumber { get; set; }
}
List<Passenger> modList = new List<Passenger>()
{
new Passenger() { Name = "Annie", PassengerID = 0,
TravelDocs = new List<TravelDoc>()
{
new TravelDoc() { DocNumber = 100, DocType = "P" }
}
},
new Passenger() { Name = "May", PassengerID = 1,
TravelDocs = new List<TravelDoc>()
{
new TravelDoc() { DocNumber = null, DocType = "" }
}
},
new Passenger() { Name = "Annie", PassengerID = 0,
TravelDocs = new List<TravelDoc>()
{
new TravelDoc() { DocNumber = 100, DocType = "P" }
}
},
new Passenger() { Name = "May", PassengerID = 1,
TravelDocs = new List<TravelDoc>()
{
new TravelDoc() { DocNumber = 200, DocType = "P" }
}
}
};
Code (Throws an error)
var passengersMod = modList.SelectMany(pax => pax.TravelDocs
.Select(doc => new { Passenger = pax, TravelDoc = doc })
.Last())
.Dump();
Code (Wrong Results)
var passengersMod = modList.SelectMany(pax => pax.TravelDocs
.Select(doc => new { Passenger = pax, TravelDoc = doc })
).Last()
.Dump();
Note: Dump() is a LINQPad extension. 😀
How can I get the result I wanted using LINQ?
Thanks in advance.
Edit:
Okay, it seems that most people gets confused with “based on names” condition. Sorry about that but unfortunately I could not think of any better words to describe the criteria (sorry). But Jon Hanna got what I meant, so thanks! Also I removed the “of anonymous types” from the title as suggested. Thanks again! 😀
Another Edit:
I have another situation similar to this with slight difference. Yes, the list was group according to some criteria (in this example by names) but instead of needing the last item from each grouping, what I need is the nth item from each grouping.
I was able to get the nth from each grouping:
modList.GroupBy(p => p.Name).Select(g => g.ToList()[index])
Years after I asked this question, Jon’s answer still helped me. How I wish I could upvote his answer twice! I hope this might help somebody else. 😀
Why not ignore anonymous types and
SelectManyand just do:It’s got nothing to do with anonymous types as per your title, but it does result in the sort of results you mention at the start of the question.