[英]How can I use LINQ to select a property and also other items of a list at the same level?
I have a List of IJapaneseDictionaryEntry
objects which are described below. 我有一个IJapaneseDictionaryEntry
对象的列表,如下所述。 Inside this are IKanji
objects. 在其中是IKanji
对象。
public interface IJapaneseDictionaryEntry
{
int Sequence { get; }
IEnumerable<IKanji> Kanjis { get; }
IEnumerable<IReading> Readings { get; }
IEnumerable<ISense> Senses { get; }
}
Where each object contains a list of IKanji
objects 每个对象都包含IKanji
对象的列表
public interface IKanji
{
string Text { get; }
IEnumerable<KanjiInformation> Informations { get; }
IEnumerable<Priority> Priorities { get; }
}
I selected the data with this query: 我通过此查询选择了数据:
List<IJapaneseDictionaryEntry> entries = dictionary.GetEntries().ToList();
I know how to do a simple query like this: 我知道如何做这样的简单查询:
var a = entries.SelectMany(x => x.Kanjis);
and how to select just the text: 以及如何只选择文本:
var a = entries.SelectMany(x => x.Kanjis).Select(x => x.Text);
But what I would like to see the text and the priorities and I am not sure how to do that. 但是我想看一下案文和优先事项,我不确定该怎么做。 What I would like to do is to get a flat output like this: 我想做的是得到一个像这样的固定输出:
kanji1 ichimango1 Newspaper1 frequency10
How can I select, order and flatten out the priorities with a select? 如何通过选择来选择,排序和整理优先级?
Something like this: 像这样:
var a = entries.SelectMany(x => x.Kanjis)
.Select(x => x.Text, Priorities1, Priorities2, Priorities3);
Note that there may be no entry for Priorities1, Priorities2 or Priorities3 请注意,可能没有优先级1,优先级2或优先级3的条目。
You would need to create an anonymous object with the properties you want to return: 您需要使用要返回的属性创建一个匿名对象:
var a = entries.SelectMany(x => x.Kanjis)
.Select(x => new { x.Text, x.Priorities });
As per your EDIT: If you want to get only those Kanjis
which have a Priority
at all, you need to add a Where
after the Select
: 根据您的编辑:如果您只想获得那些具有Priority
Kanjis
,则需要在Select
之后添加Where
:
var a = entries.SelectMany(x => x.Kanjis)
.Select(x => new { x.Text, x.Priorities })
.Where(x => x.Priorities.Any());
However I would suggest to call ToList
on x.Priorities
in order to avoid iterating the same collection twice just to determine if there are elements at all. 但是,我建议在x.Priorities
上调用ToList
,以避免只对是否有元素进行两次迭代相同的集合。 Technically you could also use the Where
in front of the Select
, but in this case you´d lose the ability to call ToList
to avoid those multiple iterations. 从技术上讲,你也可以使用Where
在前面Select
,但在这种情况下you'd失去调用的能力ToList
避开那些多次迭代。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.