There is a dictionary, for example

IDictionary<string, List<Model>> 

there is a model

 public class Model { public string Name { get; set;} public byte[] Data { get; set;} } 

How can I eliminate duplicate values ​​for Name in the entire Dictionary? Filter existing dictionary. Duplicate Value values ​​must be removed. Those. if in the key "Key1" and in the key "Key2" in the list there is a Name with the same value, then it is necessary to exclude this value for the key (no matter what)

test data

 {"key1", {"Name1", <data>}, {"Name2", <data>}, {"Name3", <data>}} {"key2", {"Name4", <data>}, {"Name2", <data>}, {"Name5", <data>}} 

result

 {"key1", {"Name1", <data>}, {"Name2", <data>}, {"Name3", <data>}} {"key2", {"Name4", <data>}, {"Name5", <data>}} 

or

 {"key1", {"Name1", <data>}, {"Name3", <data>}} {"key2", {"Name4", <data>}, {"Name2", <data>}, {"Name5", <data>}} 
  • one
    @Bald his Name is a sv-va value, not a key. And then the key? - XTL
  • one
    The author, specify more specifically what needs to be done. Filter existing dictionary or set condition before adding? - XTL
  • @Bald where are the bytes? If the author explicitly said to avoid duplicate values ​​of the sv-va Name. - XTL
  • @VetaLio corrected, you need to "Filter the existing dictionary" - user2455111
  • @ user2455111 Another question is what to do when there is a repeating value: 1) delete the record? 2) change the value of the Name itself to some default ?? - XTL

2 answers 2

 HashSet<string> uniqueNames = new HashSet<string>(); foreach (KeyValuePair<string, List<Model>> pair in dict) { foreach (Model model in pair.Value.ToList()) { if (!uniqueNames.Add(model.Name)) { pair.Value.Remove(model); } } } 
  • Why minus? comment - RusArt
  • key is lost in your answer - user2455111
  • @user where is she lost? Deletion occurs in the string pair.Value.Remove(model); . uniqueModels needed only for comparing. - RusArt
  • I'll check it out (PS: minus if I don’t put it) - user2455111
  • @ user2455111 Peeped from Bald, updated) We don’t need a dictionary, just a hash collection of names - RusArt

As a response development Ruslan Artamonov. In order not to copy the list just in order to sort it out - you can use the RemoveAll method:

 HashSet<string> uniqueNames = new HashSet<string>(); foreach (KeyValuePair<string, List<Model>> pair in dict) { pair.Value.RemoveAll(model => !uniqueNames.Add(model.Name)); } 

This method works faster on long lists (that answer had a quadratic complexity with respect to the length of the list — this one has linear complexity).

But if long lists are not supposed - it is better to use a simple nested loop for the sake of readability of the code.

  • 2
    Beautiful and concise) - RusArt