从现有列表中特定索引处的元素创建新列表

问题描述 投票:-1回答:2

我有一个列表,并希望从中创建一个新列表,但只有特定索引的元素。

例如:

// Form a new list made of people at indices 1, 3, 5, 44.
List<People> newList = existingList.ElementsAt(1,3,5,44);

我不想重新发明这个轮子,是否有一些内置方式?

c# .net collections
2个回答
2
投票
var newList = new List<People>
{
  existingList[1],
  existingList[3],
  existingList[5],
  existingList[44]
};

2
投票

试试这个:

HashSet<int> indexes = new HashSet<int>() { 1, 3, 5, 44 };
List<People> newList = existingList.Where(x => indexes.Contains(existingList.IndexOf(x))).ToList();

或者使用普通的旧for循环:

HashSet<int> indexes = new HashSet<int>() { 1, 3, 5, 44 };
List<int> newList = new List<int>();
for (int i = 0; i < existingList.Count; ++i)
    if (indexes.Contains(i))
        newList.Add(existingList[i]);
© www.soinside.com 2019 - 2024. All rights reserved.