colinfang
colinfang

Reputation: 21727

Is it worthwhile rewriting the following `Dictionary` construction using Linq, and how?

For example, i don't know if it is a good practice to use Linq whenever possible.

     Class Aclass : Dictionary<string,int>
     {
        public Aclass(Aclass myAclass, HashSet<string> blacklist)
        {
            foreach (var item in myAclass)
            {
                if ((item.Value > 0) && (!blacklist.Contains(item.Key)))
                {
                    Add(item.Key, item.Value);
                }
            }
         }
      }

Upvotes: 0

Views: 122

Answers (3)

gandarez
gandarez

Reputation: 2662

You can try by this way:

public class Aclass : System.Collections.Generic.Dictionary<string, int>
{
    public Aclass(Aclass myAclass, System.Collections.Generic.HashSet<string> blacklist)
    {
        foreach (var item in myAclass)
        {
            int iCount = (from itemBlack in blacklist
                          where itemBlack == item.Key
                          select itemBlack)
                          .Count();

            if ((item.Value > 0) && (iCount == 0))
            {
                Add(item.Key, item.Value);
            }
        }
    }
}

Upvotes: -1

Bas
Bas

Reputation: 27105

You can use linq for this:

myAclass.Where(item => item.Value > 0 && !blacklist.Contains(item.Key))
        .ToList().ForEach(item => Add(item.Key, item.Value);

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500815

It looks to me like you'd be fine with:

Dictionary<string, int> other = ...;
HashSet<string> blacklist = ...;

var dictionary = other.Where(item => item.Value > 0 && 
                                     !blackList.Contains(item.Key)
                      .ToDictionary(item => item.Key, item => item.Value);

No need for a separate type at all as far as I can see - deriving from Dictionary<,> or List<> is almost always a bad idea IMO.

Upvotes: 4

Related Questions