开发者

C# remove duplicate dictionary items from List<>?

So I a collection of dictionary items in a list:

List<Dictionary<string, string>> inputData = new List<Dictionary<string, string>>(inputs);    
List<Dictionary<string, string>> itemStack = new List<Dictionary<string, string>>();

Now what I want to do is for each inputData dictionary item I want to check if itemStack has the sam开发者_JAVA技巧e value (Dictionary Item) already.

I was thinking it would be like?

foreach (var item in inputData)
{
  if(!itemStack.Contains(item){ itemStack.Add(item)}
  else{ //Duplicate found}
}

It doesn't really check the items values inside? It just assumes that it doesn't have it... All i want is if itemStack contains and item that is already in the stack don't include it. I know I'm missing something obvious. Thanks,


Dictionary is reference type, so it doesn't check the "deep" value like you expected.

You will have to write your own "Contains" method, either as totally separate method or extension of the Dictionary itself then use it instead, for example:

 if(!MyContains(itemStack, item)){ itemStack.Add(item)}


True that a HashSet would be better, but if you want to do it here, try this (assuming you are filtering duplicate keys only):

foreach (var item in inputData.Keys)
{
    if (itemStack.Where(x => x.Key == item.Key).Count() > 0)
              // There was a duplicate
}

Or, if you only care when the data is coming out you can call:

itemStack.Distinct()


I think, your way is right. On my mind, HashSet is good, but when you add a new element, it performs the same test on the contents of the same items.

Regards.


Based on your initial problem statement, you might do something like this:

var aggregateKnownKeys = itemStack.SelectMany(d => d.Keys);
itemStack.AddRange(
    inputData.Select(d=> d.Where(p => !aggregateKnownKeys.Contains(p.Key))
                          .ToDictionary(p => p.Key, p => p.Value)));

If you only need to combine two dictionaries then you could do this to skip keys that exist in itemStack:

var inputData = new Dictionary<string, string>();
var itemStack = new Dictionary<string, string>();

var oldStack = itemStack;
itemStack = new[] { inputData.SkipWhile(d => oldStack.Keys.Contains(d.Key)), itemStack }
   .SelectMany(d => d)
   .ToDictionary(d => d.Key, d => d.Value);


Okay so this isn't quite a full answer but it's what I did.

So I have a List of items and instead of doing a full compare to whats in an List(Hence the other considered) I just did a single item check:

    if(!String.IsNullOrEmpty(item["itemId"]))
 {
    alert.DaleksApproaching(item["itemId"]);
 }

So when it does see it has a value it just does another event to get rid of it. The idea of using LINQ and the method approaches about(Contains and Distinct)I like. I have yet to try that, but I plan on doing that. For this it doesn't use LINQ :(

Thanks everyone!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜