say i have two strings string str1 = "SAKVRLW" string str2 = "TCOEFO"
The result i wanted is below
result = "STACKOVERFLOW".
Sorry if this is a basic question but i am new to Linq ? Any help/suggestions to achieve this?
say i have two strings string str1 = "SAKVRLW" string str2 = "TCOEFO"
The result i wanted is below
result = "STACKOVERFLOW".
Sorry if this is a basic question but i am new to Linq ? Any help/suggestions to achieve this?
Just for the fun of it:
string str1 = "SAKVRLW";
string str2 = "TCOEFO";
str1.ToCharArray()
.Select((ch, ix)=> new { ch=ch, ix = ix*2 })
.Concat( str2.ToCharArray().Select((ch, ix)=> new { ch=ch, ix = ix*2 +1 }))
.OrderBy(x=>x.ix)
.Select(x=>x.ch)
.Aggregate("", (s,c)=>s+c).Dump();
At the heart of this linq query is getting the index number from the select statement to use as an indexer into the other array.
Then its a matter of checking for an out of bounds condition while processing the char arrays into strings to be joined.
var str1 = "SAKVRLW";
var str2 = "TCOEFO";
var array2 = str2.ToCharArray();
string.Join(string.Empty,
str1.ToCharArray()
.Select ((ch, index) => string.Format("{0}{1}",
ch,
index < array2.Length
? array2[index].ToString()
: string.Empty
)
)
)
Outputs: STACKOVERFLOW
Using the above Select
(projection) with an Aggregate
instead of string.Join
can be done as such
str1.ToCharArray()
.Select ((ch, index) => string.Format("{0}{1}", ch, index < array2.Length ? array2[index].ToString() : string.Empty ))
.Aggregate ((seed, sentance) => seed + sentance )
Outputs: STACKOVERFLOW