1

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.

2
  • 7
    A dictionary only allows unique keys so you cannot have duplicates. Commented Dec 2, 2017 at 18:04
  • 1
    Why do you have to use linq? Commented Dec 2, 2017 at 18:14

3 Answers 3

2

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]
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.