删除与LINQ的最后一个项目 [英] Drop the last item with LINQ
问题描述
可能重复:结果
的如何采取一切但使用LINQ序列中的最后一个元素?
好像与LINQ(也许是)一个简单的任务,但我无法弄清楚如何SQUENCE的最后一个项目使用LINQ下降。使用取并通过序列的长度 - 1工程精品课程的。然而,链接起来的一行代码的多个LINQ时,这种做法似乎很inconvienient
Seems like a trivial task with LINQ (and probably it is), but I cannot figure out how to drop the last item of squence with LINQ. Using Take and passing the length of the sequence - 1 works fine of course. However, that approach seems quite inconvienient when chaining up multiple LINQ in a single line of code.
IEnumerable<T> someList ....
// this works fine
var result = someList.Take(someList.Count() - 1);
// but what if I'm chaining LINQ ?
var result = someList.Where(...).DropLast().Select(...)......;
// Will I have to break this up?
var temp = someList.Where(...);
var result = temp.Take(temp.Count() - 1).Select(...)........;
在Python中,我只是做序列[0:-1]。我试图通过-1采取的方法,但它似乎并没有做什么,我需要的。
In Python, I could just do seq[0:-1]. I tried passing -1 to Take method, but it does not seem to do what I need.
推荐答案
您可以编写自己的LINQ查询操作符(也就是上的扩展方法:// msdn.microsoft.com/en-us/library/9eekhta0.aspx> 的IEnumerable< T>
),例如:
You could write your own LINQ query operator (that is, an extension method on IEnumerable<T>
), for example:
static IEnumerable<T> WithoutLast<T>(this IEnumerable<T> source)
{
using (var e = source.GetEnumerator())
{
if (e.MoveNext())
{
for (var value = e.Current; e.MoveNext(); value = e.Current)
{
yield return value;
}
}
}
}
与其他的方法,如 xs.Take(xs.Count() - 1)
,上面会处理序列只有一次
Unlike other approaches such as xs.Take(xs.Count() - 1)
, the above will process a sequence only once.
这篇关于删除与LINQ的最后一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!