我有一个列表,并希望从中创建一个新列表,但只有特定索引的元素。
例如:
// Form a new list made of people at indices 1, 3, 5, 44.
List<People> newList = existingList.ElementsAt(1,3,5,44);
我不想重新发明这个轮子,是否有一些内置方式?
var newList = new List<People>
{
existingList[1],
existingList[3],
existingList[5],
existingList[44]
};
试试这个:
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]);