I am attempting to iter开发者_运维知识库ate 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?
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);
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);
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.
精彩评论