Home > Software engineering >  C#, Linq, .Net3.1 - create a new collection according to the conditions
C#, Linq, .Net3.1 - create a new collection according to the conditions

Time:08-15

I'm trying to solve one task with .Net 3.1 and Linq and can't succeed.

I have function which accepts one parameter type of IEnumerable and returns same type of value:

IEnumerable<string> Foo(IEnumerable<string> strCollection){}

The input parameter (strCollection) is always sorted in ascending order.

I need to select the last character from each string, converting it to uppercase, and from the received characters, compose a string.

Returned collection depends on strCollection[i].Length. Say, if strCollection contains 3 elements with length of 2 and 2 elements with length of 3, the retuned collection should have 2 elements.

Then I should arrange the resulting sequence of strings in descending order of their lengths.

Say,

if(1):

strCollection = new[] { "bc", "sd", "ac", "sdf", "ewr" };

Function should return:

new[] { "CCD", "RF" });

if(2):

strCollection = new[] { "ab", "attribute", "cheese", "swim", "cut" };

return:

new[] { "B", "E", "E", "T", "M" });

if(3):

strCollection = new[] { "du", "the", "ace", "run", "cut" };

return:

new[] { "ETNE", "U" });

if(4):

strCollection = new[] { "star", "galaxy", "quasar", "planet", "asteroid", "satellite", "comet" };

return:

new[] { "YTR", "D", "T", "E", "R" });

Here is my solution which does not works:

IEnumerable<string> Foo(IEnumerable<string> strCollection)
    {
        return stringList.OrderBy(x => x.Length).GroupBy(x => x.Length).Select(x => x.Key).Reverse().Select(x => x.ToString());
    }

Please help!

CodePudding user response:

Your can generate the required array as follows:

static IEnumerable<string> Foo(IEnumerable<string> strCollection)
{
    return strCollection.OrderBy(s => s)
        .GroupBy(s => s.Length)
        .Select(g => string.Concat(g.Where(s => s.Length > 0).Select(s => Char.ToUpper(s[s.Length-1]))))
        .OrderByDescending(s => s.Length);
}

The steps are:

  1. Order the incoming strCollection into an ascending order.

  2. Group the strings by length. Note that, as explained in the docs, the input ordering is retained by the ordering of the groups and the ordering of items within each group.

  3. For each group, concatenate the uppercase versions of the last character(s) of each string into a combined string.

  4. Finally order the sequence by string length in reverse.

Demo here.

  • Related