Home > Net >  LINQ query to group strings by first letter and determine total length
LINQ query to group strings by first letter and determine total length

Time:12-01

A sequence of non-empty strings stringList is given, containing only uppercase letters of the Latin alphabet. For all strings starting with the same letter, determine their total length and obtain a sequence of strings of the form "S-C", where S is the total length of all strings from stringList that begin with the character C.

var stringList = new[] { "YELLOW", "GREEN", "YIELD" }; 
var expected = new[] { "11-Y", "5-G" };

I tried this:

var groups =
  from word in stringList
  orderby word ascending
  group word by word[0] into groupedByFirstLetter
  orderby groupedByFirstLetter.Key descending
  select new { key = groupedByFirstLetter.Key, Words = groupedByFirstLetter.Select(x => x.Length)  };

But the output of this query is Y 6 5 G 5 instead of Y-11 G-5. What I would like to know is how to sum the lengths if there is more than 1 word in the group, and how to format the result/display it as expected?

CodePudding user response:

This should do it:

var results = stringList.GroupBy(x => x[0])
                        .Select(g => $"{g.Sum(x => x.Length)}-{g.Key}")
                        .ToArray();

CodePudding user response:

var result = stringList.GroupBy(e => e[0]).Select(e => $"{e.Sum(o => o.Length)}-{e.Key}").ToArray();

Not sure I am able to rewrite it in your form.

  • Related