Skip to main content
 首页 » 编程设计

c#之如何使用 LINQ 对对象集合进行简单的基于顺序的验证

2024年02月03日30mengfanrong

给定单个对象集合,我想确定某些对象是否只出现在另一个对象之后。

例如说我有一个字符串列表,例如

A B B b b a C c

我想检查每个小写字母在序列中是否至少有与它之前出现的大写字母一样多。因此上面的序列是无效的,因为有两个小写字母 'a' 而只有一个 'A')。但以下内容是有效的:

A B b

A B a b

A B b a

B A b

...

有没有办法使用 LINQ 做到这一点?

请您参考如下方法:

我想你的意思是 IEnumerable<char>而不是 IEnumerable<string> ?

使用 Rollup 扩展方法描述 here (“Select 和 Aggregate 扩展方法之间的交叉”),你可以这样做:

IEnumerable<char> chars = ... 
 
bool isValid = chars.Where(char.IsLetter) 
                    .GroupBy(char.ToUpperInvariant) 
                    .SelectMany(g => g.Rollup(0,  
                                (c, sum) => sum + (char.IsUpper(c) ? 1 : -1))) 
                    .All(runningTotal => runningTotal >= 0); 

为了完整起见,该方法的代码如下:

public static IEnumerable<TResult> Rollup<TSource, TResult>( 
    this IEnumerable<TSource> source, 
    TResult seed, 
    Func<TSource, TResult, TResult> projection) 
{ 
    TResult nextSeed = seed; 
    foreach (TSource src in source) 
    { 
        TResult projectedValue = projection(src, nextSeed); 
        nextSeed = projectedValue; 
        yield return projectedValue; 
    } 
}