HereToLearn
HereToLearn

Reputation: 282

C# Check If List Contains Similiar Strings Using LINQ

So I have a list that looks something like the following:

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

How can I count how many times each country is mentioned in the list and return an integer? So Canada is mentioned once (1), US is mentioned twice (2) and Japan is mentioned once (1).

Please note that the country will always be the last word in the list's element and I do not know what specific countries are in the list.

Thank you

Upvotes: 1

Views: 67

Answers (3)

loneshark99
loneshark99

Reputation: 714

You can also do this (Try in 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()

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Extract countries, and GroupBy by them:

 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));

Outcome:

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

Upvotes: 6

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

You could split each element by spaces, then group by the last token and count the number of occurrences:

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);
}

Which will print:

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

Upvotes: 0

Related Questions