2010-03-02 84 views
0

我有一个类,如下所示,它存储一个Uri对象和一个计数。我的想法是,我创建了一个UrlPackage对象列表来保存在拖网域时发现的链接以及找到它们的次数。问题是如何检查Uri是否已经添加到列表中。搜索一个列表来检查一个子对象是否已经存在

我用来直接存储的URI列表中,因此只用了以下内容:

linkList.Contains(Uri) 

但现在我想找到,如果UriPackage.UriObj列表中存在。

我在想linq是前进的道路,但不知道如何使用它。有任何想法吗?

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; } 
     } 
    } 

回答

3

您应该使用Dictionary<Uri, int>而不是列表。

您可以增加计数dict[uri]++;您可以通过dict.ContainsKey(uri)查看存在情况。

请注意,在插入新的URI之前,您需要检查状态:if (dict.ContainsKey(uri)) dict[uri]++ else dict[uri] = 1;(因为与C++通过字典中不存在的键进行索引相比是不允许的)。

0

使用

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

如果对象存在,增加它,如果没有,添加它并设置INT至1 ....

if (myList.HasKey(item)) myList[ item ]++ 
else myList.Add(item,1); 
2

尝试linkList.Any(x=>x.UriObj == uri)

更新:正如其他人提到的字典是用于索引和存储这更好。但是,上面应该做你想要的。

0
var objectExists = 
(from i in linkList where i.Uri = uriVarible select i).Any(); 
+0

没关系可选默认值,其他答案是更好的。 confusedGeek的Lamba表达式是使用Linq的更简洁的方式,但如果您担心性能问题,应该尝试使用Dictionary方法 – 2010-03-02 21:00:33

0

如果你发现你做了很多的dict.ContainsKey(key)你可能会考虑这个扩展方法。

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

,并使用这个你可以

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

其实,我觉得应该是在C#泛型字典,不得不默认这种行为,这样你可以写

dic["test"]++; 

没有得到一个例外。这方面的一个例子是Ruby的哈希类是如何发生这样的

>> h = Hash.new(0) 
>> h["test"]+=1 
=> 1 
>> h["test"]+=1 
=> 2 
相关问题