首页 / C#开发 / 正文

[LINQ].NET/C#应用程序开发中如何使用LINQ查询集合List<T>中N的倍数索引位置的所有元素?

2036 发布于: 2018-04-20 读完约需5分钟

问题描述

在.NET/C#应用程序开发中,当前有一个泛型集合List<T>,如何使用LINQ查询这个集合List<T>中索引位置在N的倍数的所有元素?

方案一

var result = list.Where((x, i) => i % nStep == 0);

方案二

使用yield return,而不使用LINQ或者Lambda表达式,如下:

IEnumerator<T> GetNth<T>(List<T> list, int n) {
  for (int i=0; i<list.Count; i+=n)
    yield return list[i]
}

当然,我们也可以把它改写成静态扩展方法,如下:

public static class MyListExtensions {
  public static IEnumerable<T> GetNth<T>(this List<T> list, int n) {
    for (int i=0; i<list.Count; i+=n)
      yield return list[i];
  }
}

如果在LINQ语句中使用:

from var element in MyList.GetNth(10) select element;

或者使用LINQ的方式实现,如下:

from var i in Range(0, ((myList.Length-1)/n)+1) select list[n*i];

方案三

写一个静态扩展方法,如下:

public static class LinqExtensions
{
    public static IEnumerable<T> GetNth<T>(this IEnumerable<T> list, int n)
    {
        if (n < 0)
            throw new ArgumentOutOfRangeException("n");
        if (n > 0)
        {
            int c = 0;
            foreach (var e in list)
            {
                if (c % n == 0)
                    yield return e;
                c++;
            }
        }
    }
    public static IEnumerable<T> GetNth<T>(this IList<T> list, int n)
    {
        if (n < 0)
            throw new ArgumentOutOfRangeException("n");
        if (n > 0)
            for (int c = 0; c < list.Count; c += n)
                yield return list[c];
    }
}

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: [LINQ].NET/C#应用程序开发中如何使用LINQ去重集合中的元素?

下一篇: [MySQL]MySQL中如何使用SQL命令行列举出数据库中所有的存储过程和函数?

本文永久链接码友网 » [LINQ].NET/C#应用程序开发中如何使用LINQ查询集合List<T>中N的倍数索引位置的所有元素?

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册