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