0

I'm trying to eliminate the duplicate strings from the list with the list.District() and the toDictionary but it doesn't work.

Any recommendation how I can eliminate the duplication code with Linq?

here is my code

    [JsonIgnore]
    public Dictionary<string, int> SensorValues => InOrderSensorValues
      .ToDictionary(
         x => x.Split(':')[0].ToUpper(), 
         x => int.Parse(x.Split(':')[1]));

And then i want to split the words as above

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Csibi Norbert
  • 780
  • 1
  • 11
  • 35
  • 1
    You're not using `Distinct` anywhere? – Darren Young Nov 12 '19 at 13:27
  • What do you mean by "it doesn't work"? What is `InOrderSensorValues`? What did you expect `SensorValues` to be? What is it actually? – Sweeper Nov 12 '19 at 13:27
  • Please provide a [mre] of the problem you are seeing. That should include a small sample of the data in `InOrderSensorValues` that produces the the duplicates. – Heretic Monkey Nov 12 '19 at 13:31
  • @Darren, I used it but I doesnt work with toDictionary – Csibi Norbert Nov 12 '19 at 13:33
  • @Sweeper, SensorValues is a simple list with a string value, such as "Sensor1:2" and I'm trying to split the string. I want to put the Sendor1 as a key into the dictionary and value of 2 etc – Csibi Norbert Nov 12 '19 at 13:35
  • @CsibiNorbert Can't you just do `Distinct` before `ToDictionary`? – Sweeper Nov 12 '19 at 13:40
  • @Sweeper i cannot, it throws an error, cannot even build – Csibi Norbert Nov 12 '19 at 13:51
  • @Sweeper That wouldn't help - the duplicate keys come from the `Split`, and a `Distinct` is against the whole object. An extension method `DistinctBy` is what would be used, or `ToLookup` then `ToDictionary`. – NetMage Nov 12 '19 at 22:08

2 Answers2

3

ToDictionary() fails on duplicate keys by design. You can either filter out your data, or insert a GroupBy() before it to eliminate duplicate entries.

Lastly, you can also consider ToLookup() which does tolerate duplicate keys.

Adding GroupBy() would be like this:

public Dictionary<string, int> SensorValues => 
     InOrderSensorValues.GroupBy(x => x.Split(':')[0].ToUpper()).
     ToDictionary(g => g.Key, g => int.Parse(g.First().Split(':')[1]));
Tanveer Badar
  • 5,438
  • 2
  • 27
  • 32
2

You can use Select to save the Split string and then GroupBy the key, then create a Dictionary using a selection method for the multiple values - I chose First:

public Dictionary<string, int> SensorValues => InOrderSensorValues
      .Select(sv => sv.Split(':'))
      .GroupBy(svp => svp[0].ToUpper(), svp => svp[1])
      .ToDictionary(
         kvp => kvp.Key, 
         kvp => int.Parse(kvp.First()));
NetMage
  • 26,163
  • 3
  • 34
  • 55