我不完全确定这是您需要的,但是通过这个小代码,我可以创建您指定的输出
简单用法(带断言):
var a1 = new List<string> { "A", "A", "B", "C", "D", "E", "E" };
a1.ApplyCriteria("A").Criteria.Should().Be("A");
a1.ApplyCriteria("A").Count.Should().Be(2);
a1.ApplyCriteria("E").Criteria.Should().Be("E");
a1.ApplyCriteria("E").Count.Should().Be(2);
a1.ApplyCriteria("BCD").Criteria.Should().Be("BCD");
a1.ApplyCriteria("BCD").Count.Should().Be(1);
a1.ApplyCriteria("CD").Criteria.Should().Be("CD");
a1.ApplyCriteria("CD").Count.Should().Be(1);
// not found
a1.ApplyCriteria("CDA").Criteria.Should().Be("CDA");
a1.ApplyCriteria("CDA").Count.Should().Be(0);
ApplyCriteria 方法返回的我的 GroupResult 类如下所示:
class GroupResult
{
public string Criteria { get; set; }
public int Count { get; set; }
}
这些是做实际工作的扩展方法
static class Ext
{
public static GroupResult ApplyCriteria(this IEnumerable<string> source, string criteria)
{
var elements = source.ToConcatenedString();
return new GroupResult { Criteria = criteria, Count = elements.CountOcurrences(criteria) };
}
public static int CountOcurrences(this string source, string phrase)
{
return source
.Select((c, i) => source.Substring(i))
.Count(sub => sub.StartsWith(phrase));
}
public static string ToConcatenedString<TSource>(this IEnumerable<TSource> source)
{
var sb = new StringBuilder();
foreach (var value in source)
{
sb.Append(value);
}
return sb.ToString();
}
}