C# 如何使用 LINQ 从列表中选择提供的索引范围内的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1042087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to select values within a provided index range from a List using LINQ
提问by Punit Vora
I am a LINQ newbie trying to use it to acheive the following:
我是一个 LINQ 新手,试图用它来实现以下目标:
I have a list of ints:-
我有一个整数列表:-
List<int> intList = new List<int>(new int[]{1,2,3,3,2,1});
Now, I want to compare the sum of the first three elements [index range 0-2] with the last three [index range 3-5] using LINQ. I tried the LINQ Select and Take extension methods as well as the SelectMany method, but I cannot figure out how to say something like
现在,我想使用 LINQ 比较前三个元素 [索引范围 0-2] 与后三个 [索引范围 3-5] 的总和。我尝试了 LINQ Select 和 Take 扩展方法以及 SelectMany 方法,但我不知道如何说
(from p in intList
where p in Take contiguous elements of intList from index x to x+n
select p).sum()
I looked at the Contains extension method too, but that doesn't see to get me what I want. Any suggestions? Thanks.
我也查看了 contains 扩展方法,但这并没有得到我想要的。有什么建议?谢谢。
采纳答案by Adam Sills
回答by Tao
For larger lists, a separate extension method could be more appropriate for performance. I know this isn't necessary for the initial case, but the Linq (to objects) implementation relies on iterating the list, so for large lists this could be (pointlessly) expensive. A simple extension method to achieve this could be:
对于较大的列表,单独的扩展方法可能更适合性能。我知道这对于初始情况不是必需的,但是 Linq(到对象)实现依赖于迭代列表,因此对于大型列表,这可能(毫无意义)昂贵。实现此目的的简单扩展方法可能是:
public static IEnumerable<TSource> IndexRange<TSource>(
this IList<TSource> source,
int fromIndex,
int toIndex)
{
int currIndex = fromIndex;
while (currIndex <= toIndex)
{
yield return source[currIndex];
currIndex++;
}
}
回答by Onuralp
You can use GetRange()
您可以使用 GetRange()
list.GetRange(index, count);
回答by stomy
To filter by specific indexes (not from-to):
要按特定索引(不是 from-to)过滤:
public static class ListExtensions
{
public static IEnumerable<TSource> ByIndexes<TSource>(this IList<TSource> source, params int[] indexes)
{
if (indexes == null || indexes.Length == 0)
{
foreach (var item in source)
{
yield return item;
}
}
else
{
foreach (var i in indexes)
{
if (i >= 0 && i < source.Count)
yield return source[i];
}
}
}
}
For example:
例如:
string[] list = {"a1", "b2", "c3", "d4", "e5", "f6", "g7", "h8", "i9"};
var filtered = list.ByIndexes(5, 8, 100, 3, 2); // = {"f6", "i9", "d4", "c3"};