C# 计算对象中字符串中的多个特定匹配项

C# 计算对象中字符串中的多个特定匹配项,c#,.net,regex,linq,lambda,C#,.net,Regex,Linq,Lambda,我有一个来自示例类元素的列表- class SampleClass { public string Name {get; set;} } 上面的Lambda只获取与Coitans()中的模式完全匹配的前2个元素。 使用某些Lambda或某些表达式无法再次匹配与前2个同名但每次都以数字结尾的元素,并获取它们的Count()-HelloStackOverflow和HelloStackOverflow1有多少个元素?如果要获取两个单独的计数器,计算有多少实例包含HelloStackOverflow,

我有一个来自示例类元素的列表-

class SampleClass
{
public string Name {get; set;}
}
上面的Lambda只获取与Coitans()中的模式完全匹配的前2个元素。
使用某些Lambda或某些表达式无法再次匹配与前2个同名但每次都以数字结尾的元素,并获取它们的Count()-HelloStackOverflow和HelloStackOverflow1有多少个元素?

如果要获取两个单独的计数器,计算有多少实例包含
HelloStackOverflow
,然后计算有多少实例包含
HelloStackOverflow
,后跟一个数字,您可以使用正则表达式来表示后者:

var countNumber = listWithString.Where(x => x.Name.Contains("HelloStackOverflow")).Count();
var listWithString=新列表{“HelloStackOverflow”、“HelloStackOverflow”、“HelloStackOverflow9”};
var justTextCount=listWithString.Count(x=>x.Contains(“HelloStackOverflow”);
var textWithNumberCount=listWithString.Count(x=>Regex.IsMatch(x,@“HelloStackOverflow\d+”);
HelloStackOverflow和HelloStackOverflow9有多少个元素

如果我正确理解了您的问题,那么您可以使用
GroupBy
获取每个项目的出现次数:

var listWithString = new List<string> {"HelloStackOverflow", "HelloStackOverflow", "HelloStackOverflow9"};
var justTextCount = listWithString.Count(x => x.Contains("HelloStackOverflow"));
var textWithNumberCount = listWithString.Count(x => Regex.IsMatch(x, @"HelloStackOverflow\d+"));

是否要计算HelloStackOverflows<代码>HelloStackOverflow12
HelloStackOverflow0
?对我来说,您似乎正在接收
包含的内容
应该适用于此,如果它与精确的字符串匹配,它将是
==
您的字符串列表是否与原始代码有大小写差异?我自己运行它,并获得3作为计数
var listWithString = new List<string> {"HelloStackOverflow", "HelloStackOverflow", "HelloStackOverflow9"};
var justTextCount = listWithString.Count(x => x.Contains("HelloStackOverflow"));
var textWithNumberCount = listWithString.Count(x => Regex.IsMatch(x, @"HelloStackOverflow\d+"));
Dictionary<string, int> occurences = listWithString
            .GroupBy(item => item)
            .ToDictionary(grouping => grouping.Key, grouping => grouping.Count());
HelloStackOverflow -> 2
HelloStackOverflow9 -> 1