Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LINQ expression to retrieve IEnumerable of properties from IEnumerable of POCO

Tags:

c#

linq

I am attempting to iterate an IEnumerable of an object using LINQ, and pull out a certain property of every object into an IEnumerable of the type of that property.

I am currently doing it with the SelectMany LINQ expression, but instead of returning an IEnumerable<string> which I want (as the property is a string), it is returning an IEnumerable<char>

var propertyValues = objectCollection.SelectMany(o => o.Value);

What am I missing?

like image 343
jcvandan Avatar asked May 13 '11 11:05

jcvandan


3 Answers

If it is returning an IEnumerable<char> then that is what it is. At a guess you want to use Select() and not SelectMany(), I would guess it is flattening a bunch of strings as an IEnumerable<char>. If you can post more code that shows what is in objectCollection we might be able to help more.

EDIT

bit more code to illustrate my point

List<string> stringList = new List<string>();
stringList.Add("string1");
stringList.Add("string2");
IEnumerable<char> chars = stringList.SelectMany(x => x);
like image 146
Ben Robinson Avatar answered Nov 01 '22 17:11

Ben Robinson


you want Select instead of SelectMany. SelectMany will flatten a sequence of sequences. You're basically projecting to a sequence of strings - and a string is a sequence of characters, so Selectmany is flattening the sequence of strings to a single sequence of characters.

Try:

var propertyValues = objectCollection.Select(o => o.Value);
like image 5
Jon Skeet Avatar answered Nov 01 '22 18:11

Jon Skeet


Use Select(o => o.Value). SelectMany flattens collections, so it's selecting all your string Value properties, then flattens each into a list of chars.

like image 2
Tim Rogers Avatar answered Nov 01 '22 18:11

Tim Rogers