简体   繁体   中英

How to get a SubList from a list based on indices in another List?

So, I have 2 lists ,, one contains Objects and another indices of the objects I want from the 1st.

I was wondering if there is a way in C# to get a sub-list based on indices stored in another list?
I'm new to Linq and google didn't answer me yet.
also what's the Python -ic way of doing so?

Of course, i'm already using simple loops to achieve that!

List<int> IndexList;
List<int> ObjList;
List<int> subList;


foreach ( var index in IndexList )
    subList.Add(ObjList[index]);

You can write a query that includes the index as well as the item, so that you can see if IndexList contains the index, and only select those items:

List<int> subList = ObjList
    .Where((item, index) => IndexList.Contains(index))
    .ToList();
items = ["a","b","c"]
indexes = [1,2]
mappedList = list(filter(lambda item: items.index(item) in indexes, items))
print(mappedList) # prints: ['b', 'c']

To supplement Rufus L's c# answer with a python implementation.

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