Reputation: 273
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.
Upvotes: 1
Views: 1165
Reputation: 22866
Connection String Builder is more apropriate for parsing connection strings, but it keeps the last value:
new System.Data.Odbc.OdbcConnectionStringBuilder(
"Host = local;UserName = UID; Password = PWD;Host =localhost")
results in:
Key Value
host localhost
username UID
password PWD
Upvotes: 0
Reputation: 13146
As @Sedat Kapanoglu described; you shouldn't add duplicate item. You should check it before adding. So, to remove duplicates, you can perform it like this;
var keyValue = conString.Split(';')
.Where(kvp => kvp.Contains('='))
.Select(kvp => kvp.Split(new char[] { '=' }, 2))
.GroupBy(kvp => kvp[0])
.Select(kvp => kvp.FirstOrDefault())
.ToDictionary(kvp => kvp[0].Trim(), kvp => kvp[1].Trim(), StringComparer.InvariantCultureIgnoreCase);
Upvotes: 1
Reputation: 13652
You could try this LINQ query:
var d = sp.Select(x => x.Split('='))
.GroupBy(x => x[0])
.Select(x => x.First())
.ToDictionary(x => x[0], x=> x[1]);
Result:
[Host , local]
[UserName , UID]
[Password , PWD]
Upvotes: 2