【问题标题】:Return elements between two variable indexes in a list返回列表中两个变量索引之间的元素
【发布时间】:2015-06-12 11:19:00
【问题描述】:

我想返回列表中两个变量索引之间的元素。

例如,给定这个列表 -

List<int> list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

我想使用索引值的变量遍历列表。我们将索引值称为 X 和 Y。 因此,如果 X 等于索引值 0 并且 Y 等于值 5,我需要遍历索引 0-5 并返回所有元素值。例如,X 和 Y 稍后可能成为 5 到 8 的索引值。 我将如何做到这一点?

【问题讨论】:

  • 按给定的列表索引或列表值?
  • 到底是什么问题或疑问?就目前而言,您似乎可以简单地编写您在 C# 中描述的内容。
  • 对不起 O. R. Mapper,我会输入代码,但我仍在学习,不知道如何操作。

标签: c# .net linq list


【解决方案1】:

您可以使用Enumerable.SkipEnumerable.Take

var res = list.Skip(noOfElementToSkip).Take(noOfElementsToTake);

使用变量作为索引

var res = list.Skip(x).Take(y-x+1);

注意您需要将开始元素索引传递给Skip,并且要获取元素数量您需要在Take参数中传递您想要的元素数量减去开始元素数量,加一个列表为零- 基于索引。

【讨论】:

  • 我的意思是我要完善我的答案以给出 OP 真正想要的东西,这就是你的建议。
  • 我觉得应该是Take(y-x+1)
  • 所以如果 X 等于索引值 0 并且 Y 等于值 5,我需要遍历索引 0-5 并返回所有元素值 @麦肯
【解决方案2】:

你可以使用List.GetRange

var result = list.GetRange(X, Y-X+1);

或者一个简单的for循环

List<int> list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int i = X; i <= Y; i++)
{
    Console.WriteLine(list[i]);
}

或以你想要的方式重新发明轮子

public static class Extensions
{
    public static IEnumerable<T> GetRange<T>(this IList<T> list, int startIndex, int endIndex)
    {
        for (int i = startIndex; i <= endIndex; i++)
        {
            yield return list[i];
        }
    }
}

foreach(var item in list.GetRange(0, 5))
{
     Console.WriteLine(item);
}

【讨论】:

  • 谢谢医生!!!! , List.GetRange 是我需要的。我创建了一个新列表 List newlist = list.GetRange(X, Y - X + 1);现在我可以遍历该列表以获取正是我需要的元素值。
  • @KevinMoore 由于这显然是您选择的答案,请使用答案旁边的复选标记按答案标记。
  • @Mackan,哈,堆栈交换的新手..完成。我也喜欢所有其他答案,但 GetRange 是完美的。这个表格太棒了!感谢所有快速、出色的回复。
【解决方案3】:
int x = 0, y = 5;
List<int> list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (; x < y; x++)
{
    Console.WriteLine(list[x]);
}

如果 X 总是小于 Y,这将起作用。 如果您不知道哪个更大,请在循环之前添加:

 if (x > y) 
 {
      x = x ^ y;
      y = y ^ x;
      x = x ^ y;
  }

【讨论】:

  • Interlocked.Exchange怎么样?
【解决方案4】:

另一种选择:

int X = 0, Y = 5;
Enumerable.Range(X, Y - X + 1)
.Select(index => list[index]);

【讨论】:

    【解决方案5】:

    它应该可以解决问题 -

            List<int> list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    
            int startindex = 1;
            int endIndex = 7;
            var subList = list.Skip(startindex).Take(endIndex - startindex-1).ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-20
      • 1970-01-01
      • 2020-12-01
      • 2013-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多