I have tried below code to remove duplicate key from dictionary before adding it.
Sample code:
string conString = "Host = local;UserName = UID; Password = PWD;Host =localhost";
var sp = conString.Split(';');
Dictionary<string, string> keyValue = new Dictionary<string, string>();
foreach (var k in sp)
{
if (k.Contains('='))
{
var conSP = k.Split(new char[] { '=' }, 2);
if (keyValue.All(i =>
i.Key != conSP[0]))
keyValue.Add(conSP[0], conSP[1]);
}
}
Sample Result:
KeyValue[0].Key = Host, KeyValue[0].Value = local
KeyValue[1].Key = username, KeyValue[1].Value = UID
KeyValue[2].Key = Password, KeyValue[2].Value = PWD
But I need same result using linq. So I tried below code with linq to get output.
var keyValue = conString.Split(';')
.Where(kvp => kvp.Contains('='))
.Select(kvp => kvp.Split(new char[] { '=' }, 2))
.ToDictionary(kvp => kvp[0].Trim(),kvp => kvp[1].Trim(),StringComparer.InvariantCultureIgnoreCase);
But in this code I got the below exception.
"An item with the same key has already been added"
Can anyone suggest me how to resolve this?
Thanks in advance.