Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Convert delimited string array w/ duplicates to dictionary using LINQ

Tags:

c#

linq

Given

string[] array = new string[]
{
   "Sample1:foo",
   "Sample2:bar",
   "Sample1:foo1"
}

I know I can convert it to a dictionary this way:

Dictionary<string, string> whatever = new Dictionary<string, string>
foreach (string s in array) do...
  string sampleNumber = s.Substring(0, indexOfColon);
  string fooOrBar= s.Substring(indexOfColon + 1);
  whatever[sampleNumber] = fooOrBar;

And this will prevent an aggregate exception being thrown when a duplicate key is added (although overriding the key, which is fine in this case). Can I do this with LINQ? I am trying something along the lines of:

Dictionary<string, string> whatever = array.ToDictionary(
 key => key.Split(':')[0], value => value.Split(':')[1]);

Is there a way to do this without creating a lookup beforehand?

like image 979
dev way Avatar asked Dec 19 '25 20:12

dev way


1 Answers

Try this:

Dictionary<string, string> whatever =
    array
        .Reverse()
        .GroupBy(key => key.Split(':')[0])
        .SelectMany(x => x.Take(1))
        .ToDictionary(key => key.Split(':')[0], value => value.Split(':')[1]);

It gives:

whatever

Or you could do this:

Dictionary<string, string> whatever =
    array
        .Aggregate(
            new Dictionary<string, string>(),
            (d, v) => { d[v.Split(':')[0]] = v.Split(':')[1]; return d; });

Same result.

like image 185
Enigmativity Avatar answered Dec 21 '25 11:12

Enigmativity