tags:

views:

90

answers:

6

I have a class as shown below that stores a Uri object and also a count. The idea is that I create a list of UrlPackage objects to hold Links found when trawling a domain and a count of how many times they were found. The problem is how to check if a Uri has already been added to the list.

I used to store the Uri's directly in a list therefore just used the following:

linkList.Contains(Uri)

But now I want to find if UriPackage.UriObj exists within List.

I'm thinking linq is the way forward but not sure how to use it. Any ideas?

class UrlPackage
    {
        private Uri _UriObj;
        private int _Count;

        public int Count
        {
            get { return _Count; }
            set { _Count = value; }
        }

        public Uri UriObj
        {
            get { return _UriObj; }
            set { _UriObj = value; }
        }
    }
A: 

use a

Dictionary< UrlPackage, int > myList = new Dictionary< UrlPackage, int >();

if the object exists, increment it, if not, add it and set the int to 1....

if ( myList.HasKey( item ) ) myList[ item ]++
else myList.Add(item,1);
Muad'Dib
+3  A: 

You should use Dictionary<Uri, int> instead of the list.

You can increase count by dict[uri]++; you can check presence by dict.ContainsKey(uri).

Note that you'd need to check presence before inserting new uri: if (dict.ContainsKey(uri)) dict[uri]++ else dict[uri] = 1; (because in contrast to C++ indexing by the key not present in the dictionary is not allowed).

Vlad
+2  A: 

try linkList.Any(x=>x.UriObj == uri)

Update: As others mentioned Dictionary would be better for indexing and storing this. However the above should do what you want.

confusedGeek
A: 
var objectExists = 
(from i in linkList where i.Uri = uriVarible select i).Any();
Mike Mooney
Nevermind, the other answers are better. confusedGeek's Lamba expression is a more concise way to use Linq, but if you are worried about performance you should try the Dictionary approach
Mike Mooney
A: 

Hi SocialAddict,

use the Find-method with the use of a predicate.

You will find an expressive example here: http://msdn.microsoft.com/en-us/library/x0b5b5bc.aspx

henchman
A: 

If you find out that you do a lot of dict.ContainsKey(key) you might consider this extension method.

public static TValue GetValue<TKey, TValue>(this IDictionary<TKey, TValue> source, TKey key)
{
  TValue result;
  return source.TryGetValue(key, out result) ? result : default(TValue);
}

and using this you can

var dic = new Dictionary<string, int>();
dic["test"] = dic.GetValue("test") + 1;

I actually think there should be a generic Dictionary in C# that had this behavior by default so that you could write

dic["test"]++;

without getting an exception. An example of that is how the Hash class in Ruby takes an optional default value like this

>> h = Hash.new(0)
>> h["test"]+=1
=> 1
>> h["test"]+=1
=> 2
Jonas Elfström