Home > Net >  Grouping sequences with linq
Grouping sequences with linq

Time:01-20

My task is: 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. Order the resulting sequence in descending order of the numerical values of the sums, and for equal values of the sums, in ascending order of the C character codes. Everything needs to be done in one line via linq.

I tried this:

return stringList.GroupBy(x => x.FirstOrDefault())
    .Select(x => x.ToString().Length   "-"   x.Key)
    .OrderByDescending(g => g.Length)
    .ThenBy(g => g.FirstOrDefault());

But this one does not work properly.

CodePudding user response:

The following method will take a list of strings and returns the results as you have asked for:

IEnumerable<string> ProcessValues(IEnumerable<string> strings) {
    return strings.GroupBy(s => s.FirstOrDefault())
                  .Select(group => (Character: group.Key, Length: group.Sum(s => s.Length)))
                  .OrderByDescending(g => g.Length)
                  .ThenBy(g => g.Character)
                  .Select(g => $"{g.Length}-{g.Character}");
}

An example of the results you can expect is provided below:

var stringList = new List<string> { "Hello", "How", "Are", "You", "Today" }
var result = ProcessValues(stringList); // { "8-H", "5-T", "3-A", "3-Y" }

CodePudding user response:

stringList
.GroupBy(x => x.FirstOrDefault())
.Select(group => (group.Key, group.Aggregate(0, (n, s) => n   s.Length)))
.OrderByDescending(x=>x.Item2)
.ThenBy(x=>x.Item1)
.Select(x=>$"{x.Item1}-{x.Item2}");
  • Related