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

时间:2018-12-28 15:47:27

标签: c# .net collections

我有一个列表,想从中创建一个新列表,但仅在特定索引的元素之外。

例如:

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

我不希望在此轮子上重新发明轮子,是否有一些内置方法?

2 个答案:

答案 0 :(得分: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]);

答案 1 :(得分:2)

var newList = new List<People>
{
  existingList[1],
  existingList[3],
  existingList[5],
  existingList[44]
};