简体   繁体   English

使用Linq在两个记录之间获取记录

[英]Getting records in between two records using Linq

I have a list of objects and need to get the list of records from this list. 我有一个对象列表,需要从该列表中获取记录列表。 like I have of Countries and I need to get the list of countries which are in between country with name "Australia" and country "Indonasia", the list will not be sorted. 就像我具有“国家/地区”一样,我需要获取名称为“ Australia”的国家/地区与“ Indonasia”的国家/地区之间的国家/地区列表,因此不会对列表进行排序。

Am using c#. 我正在使用c#。

I tried to use something like, get the index of first and second and then use that to get the list with a for loop, but would be handy if it can be done in single query. 我试图使用类似的方法,先获取第一和第二个索引,然后使用它来获取带有for循环的列表,但是如果可以在单个查询中完成,那将很方便。

If you do the following: 如果您执行以下操作:

var elementsBetween = allElements
        .SkipWhile(c => c.Name != "Australia")
        .Skip(1) // otherwise we'd get Australia too
        .TakeWhile(c => c.Name != "Indonasia");

you'll get the result you want without iterating through the list 3 times. 您无需遍历列表3次即可获得所需的结果。

(This is assuming your countries are eg Country items with a Name string property.) (这是假设您的国家Country是例如具有Name字符串属性的Country项目。)

Note that this doesn't sort the countries at all - it's unclear from your question whether you want this or not but it's trivial to add an OrderBy before the SkipWhile . 请注意,这根本无法对国家/地区进行排序-从您的问题中尚不清楚您是否OrderBy ,但是在SkipWhile之前添加OrderBy并不容易。

这应该做的工作

var query = data.SkipWhile(x => x != "Australia").TakeWhile(x => x != "Indonesia")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM