使用 LINQ 表达式从 POCO 的 IEnumerable 检索属性的 IEnumerable
我正在尝试使用 LINQ 迭代对象的 IEnumerable,并将每个对象的某个属性提取到该属性类型的 IEnumerable 中。
我目前正在使用 SelectMany LINQ 表达式执行此操作,但它不是返回我想要的 IEnumerable
(因为该属性是字符串),而是返回一个 IEnumerable
var propertyValues = objectCollection.SelectMany(o => o.Value);
我缺少什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果它返回一个
IEnumerable
那么它就是这样。猜测您想使用 Select() 而不是 SelectMany(),我猜它是将一堆字符串压平为IEnumerable
。如果您可以发布更多代码来显示objectCollection
中的内容,我们也许能够提供更多帮助。编辑
更多代码来说明我的观点
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 anIEnumerable<char>
. If you can post more code that shows what is inobjectCollection
we might be able to help more.EDIT
bit more code to illustrate my point
您需要
Select
而不是SelectMany
。SelectMany
将展平一系列序列。您基本上是投影到字符串序列 - 而字符串是字符序列,因此 Selectmany 会将字符串序列展平为单个字符序列。尝试:
you want
Select
instead ofSelectMany
.SelectMany
will flatten a sequence of sequences. You're basically projecting to a sequence of strings - and a string is a sequence of characters, soSelectmany
is flattening the sequence of strings to a single sequence of characters.Try:
使用
Select(o => o.Value)
。 SelectMany 会展平集合,因此它会选择所有字符串Value
属性,然后将每个属性展平为字符列表。Use
Select(o => o.Value)
. SelectMany flattens collections, so it's selecting all your stringValue
properties, then flattens each into a list of chars.