【问题标题】:Create a new list out of elements at specific indices in an existing list使用现有列表中特定索引处的元素创建新列表
【发布时间】:2018-12-28 15:47:27
【问题描述】:

我有一个列表,并想从中创建一个新列表,但仅限于特定索引处的元素。

例如:

// 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


【解决方案1】:
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]);
    

    【讨论】:

    • 本来我是这么想的,但是当 OP 知道要提取哪些元素时,循环遍历列表会不会有点多?
    • 这取决于索引在编译时是已知的还是动态的。
    • 编译时已知。我正在使用它进行单元测试,参数匹配。
    猜你喜欢
    • 1970-01-01
    • 2015-10-13
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多