C#检查List是否包含使用LINQ的类似字符串

时间:2017-04-26 18:37:00

标签: c# list linq

所以我有一个类似于以下内容的列表:

{"Apples Oranges Canada", "Fruit Apples US", "Food Something US", "Another Word Japan"}

如何计算列表中每个国家/地区提交的次数并返回整数?因此,加拿大被提及一次(1),美国被提及两次(2),日本被提及一次(1)。

请注意,该国家/地区始终是列表元素中的最后一个字词,而我知道列表中的特定国家/地区。

谢谢

3 个答案:

答案 0 :(得分:6)

提取国家/地区,GroupBy由他们提供:

 string[] source = new string[] {
   "Apples Oranges Canada", "Fruit Apples US", "Food Something US", "Another Word Japan"};

 var result = source
   .GroupBy(item => item.Substring(item.LastIndexOf(' ') + 1))
   .OrderBy(chunk => chunk.Key)
   .Select(chunk => $"{chunk.Key,-8} appears {chunk.Count()} times");

Console.Write(string.Join(Environment.NewLine, result));

结果:

Canada   appears 1 times
Japan    appears 1 times
US       appears 2 times       

答案 1 :(得分:0)

您可以按空格分割每个元素,然后按最后一个标记分组并计算出现次数:

var data = new[] { "Apples Oranges Canada", "Fruit Apples US", "Food Something US", "Another Word Japan" };
var result = data.GroupBy(x =>
{
    var tokens = x.Split(' ');
    var country = tokens[tokens.Length - 1];
    return country;
})
.Select(g => new
{
    Country = g.Key,
    Count = g.Count(),
});

foreach (var item in result)
{
    Console.WriteLine("Country: {0}, Count: {1}", item.Country, item.Count);
}

将打印:

Country: Canada, Count: 1
Country: US, Count: 2
Country: Japan, Count:

答案 2 :(得分:0)

你也可以这样做(试试Linqpad)

var data = new[] { "Apples Oranges Canada", "Fruit Apples US", "Food Something US", "Another Word YASH" };
var result = data.GroupBy(x => x.Split(' ').LastOrDefault(),(a, b) => new { Country = a, Count = b.Count()});
result.Dump()