-1

I have the following code:

var strings = new List<string>() { "012abc", "120ccc", "000aaa" };
var str = strings.Select(x => x.ToCharArray());

I need to get the max string on each position returned as a string.

  • Position 1: 0, 1 and 0 = 1
  • Position 2: 1, 2 and 0 = 2

Resulting string should be: 122ccc.

Is there a Lambda / Linq query that can be used for this or do I just need to loop through each character?

aloisdg
  • 22,270
  • 6
  • 85
  • 105
CyclingFreak
  • 1,614
  • 2
  • 21
  • 40

1 Answers1

3

I supposed that length of all strings is equal

Solution 1: without using Linq.

The idea is: Get max char at the position i in the loop

var strings = new List<string>() { "012abc", "120ccc", "000aaa" };
var arrays = strings.Select(x => x.ToCharArray());

var charResult = new List<char>();

for(int i = 0; i < strings.First().Length;i++)
{
    charResult.Add(arrays.Select(x=> x[i]).Max());
}           

Output :

122ccc

Solution 2: with Linq

The fiddle works: https://dotnetfiddle.net/MPA8RA

The idea: use Aggregate to compare each pair of char[].

var strings = new List<string>() { "012abc", "120ccc", "000aaa" };
var arrays = strings.Select(x => x.ToCharArray());          

var charResult = arrays.Aggregate((a, b) => b.Select((t,i) => (char)Math.Max(t, a[i])).ToArray());          

Console.Write(new string(charResult.ToArray()));

Output :

122ccc
aloisdg
  • 22,270
  • 6
  • 85
  • 105
Antoine V
  • 6,998
  • 2
  • 11
  • 34
  • "without looping" – Sayse Aug 01 '18 at 09:37
  • Nice use of Aggregate :) Note that you can replace `new string(charResult.ToArray())` with `string.Concat(charResult)` – aloisdg Aug 01 '18 at 09:58
  • 1
    As an experiment in my answer https://stackoverflow.com/a/51584267/6230863 , new string is the fastest way. So, I like to use it – Antoine V Aug 01 '18 at 09:59
  • You don't need `arrays = strings.Select(x => x.ToCharArray());` - you can just use `strings` where you are using `arrays`. That will save a few cycles. Also instead of `strings.First().Length` you can just use `strings[0].Length` – Matthew Watson Aug 01 '18 at 10:44
  • `As an experiment in my answer stackoverflow.com/a/51584267/6230863 , new string is the fastest way` I looked at your test code, but I note that it does not account for the extra pressure on the GC caused by creating an additional array with the `.ToArray()` so therefore the results are a little suspect IMO. – Matthew Watson Aug 01 '18 at 10:53