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

Viewed 623

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?

4 Answers
Related