1

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

2
  • What have you tried? If you haven't tried anything yet, I'd start with figuring out how to isolate the last word in each string. Commented Apr 26, 2017 at 18:42
  • 1
    " the country will always be the last word"...famous last words. Commented Apr 26, 2017 at 18:49

3 Answers 3

6

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       
Sign up to request clarification or add additional context in comments.

1 Comment

Substring, nice touch.
0

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:

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.