简体   繁体   中英

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.

Am using 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.

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.

(This is assuming your countries are eg Country items with a Name string property.)

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 .

这应该做的工作

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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