还有就是要算它符合一些条件的元素数量的标准方式:LINQ查询问题
collection.Where(d=> d==something).Count();
我需要以下功能(伪COD):
collection.Where(d=> (d==something) && (d.Next == somethingElse)).Count();
编辑:d.Next - 是集合中d之后的下一个元素。
这是如何实现的?
还有就是要算它符合一些条件的元素数量的标准方式:LINQ查询问题
collection.Where(d=> d==something).Count();
我需要以下功能(伪COD):
collection.Where(d=> (d==something) && (d.Next == somethingElse)).Count();
编辑:d.Next - 是集合中d之后的下一个元素。
这是如何实现的?
假设你所拥有的是一个涉及源序列中连续元素的谓词,你可以这样做:
int numMatches = collection.Zip(collection.Skip(1), (prev, next) =>
prev == something && next == somethingElse)
.Count(match => match)
在应用过滤器之前,这会在序列的一个延迟版本上叠加序列。
var result = collection.Count(d =>
d == something &&
d.Next == somethingElse
);
编辑:的情况下,如果d.Next
的d
属性或序列中的下一个元素:
var result = collection.Zip(
collection.Skip(1),
(first, second) => first == something && second == somethingElse
).Count(i => i);
可以写一个新的操作符(假定LINQ到对象)明确地使用枚举器来检查它。
代码:
public static partial class Enumerable
{
public static IEnumerable<TSource> WhereNext<TSource> (this IEnumerable<TSource> source, Func<TSource, bool> predicate, TSource next)
{
if (source == null)
throw new ArgumentNullException("source");
if (predicate == null)
throw new ArgumentNullException("predicate");
return WhereNextImpl(source, predicate, next);
}
private static IEnumerable<TSource> WhereNextImpl<TSource>(IEnumerable<TSource> source, Func<TSource, bool> predicate, TSource next)
{
using (var enumerator = source.GetEnumerator())
{
TSource current;
TSource nextElement;
if (!enumerator.MoveNext())
yield break;
while (true)
{
current = enumerator.Current;
if (!enumerator.MoveNext())
yield break;
nextElement = enumerator.Current;
if (predicate(current) && EqualityComparer<TSource>.Default.Equals(next, nextElement))
yield return current;
}
}
}
}
警告:目前使用EqualityComparer<TSource>.Default
的比较。应使用自定义比较器的另一个实现。
如果集合是stirng的列表,你可以尝试像涉及让利
var selectC = from c in collection
let nextC = collection.IndexOf(c) == collection.Count - 1 ? null : collection[collection.IndexOf(c) + 1]
where string.IsNullOrEmpty(c) && string.IsNullOrEmpty(nextC)
select c;
查询是棘手转化为方法链,但我得到这个从ReSharper的自动转换
var selectC =
collection.Select(
c =>
new {c, nextC = collection.IndexOf(c) == collection.Count - 1 ? null : collection[collection.IndexOf(c) + 1]}).
Where(@t => string.IsNullOrEmpty(@t.c) && string.IsNullOrEmpty(@t.nextC)).Select(@t => @t.c);
可以使用Aggregate Method创建自定义的总和:
var result = collection.Aggregate(
Tuple.Create(false, 0),
(s, x) => Tuple.Create(x == something,
s.Item1 + (s.Item0 && (x == somethingElse) ? 1 : 0)),
s => s.Item1);
它的工作原理是这样的:
Item Accumulator --------------- --------------- (false, 0) foo (false, 0) something (true, 0) bar (false, 0) something (true, 0) somethingElse (false, 1) somethingElse (false, 1) baz (false, 1) --------------- Result: 1
有趣的实现。 – Peter17 2011-03-05 16:05:54
是'd.Next' D'或'的属性序列中的下一个元素? – Ani 2011-03-05 14:56:10
不,下一个是集合中的下一个元素。 – Peter17 2011-03-05 15:00:54