开发者

Storing complex data in a list

I'm working with a product called SiteFinity.

I have a class which looks like so:

public class Categories
{    
    public IContent oContent {get; set;}    
}

I'm then looping through a list and trying to check whether the current value already exists, like so:

IList items = base.CreateDataSource();
IList filteredList = new List<string>();

foreach (IContent cnt in items)
{
   if (!filteredList.Contains(cnt))
    {
        filteredList.Add(cnt);
    }
}
return filteredList;

But this returns an error. Am i using the .Contains correctly?

Update:

Ok I have updated:

List<IContent> filteredList = new List<IContent>();

However, IContent has a method that can be called to extract further information, which is like so:

foreach(IContent cnt in i开发者_开发技巧tems)
{
    string strCat = cnt.GetMetaData("Category");
}

Now although i want filteredList to contain multiple IContent items, I want to check against the string GetMetaData before deciding whether the item should be added. Does that make sense?

Thanks.


You need to change:

   System.Collections.IList filteredList = new List<string>();

to

   List<IContent> filteredList = new List<IContent>();

Update

It sounds like you need to have IContent implement IEquatable<T> since this is the interface that List<T>.Contains looks for when making the comparison. Then inside Equals, compare the string values.

The IEquatable interface is used by generic collection objects such as Dictionary, List, and LinkedList when testing for equality in such methods as Contains, IndexOf, LastIndexOf, and Remove. It should be implemented for any object that might be stored in a generic collection.

And as the notes mention, dont forget:

If you implement IEquatable, you should also override the base class implementations of Object.Equals(Object) and GetHashCode so that their behavior is consistent with that of the IEquatable.Equals method. If you do override Object.Equals(Object), your overridden implementation is also called in calls to the static Equals(System.Object, System.Object) method on your class. This ensures that all invocations of the Equals method return consistent results.

Here is an example.


You cannot add your IContent object to a List<string>, since a List<String> can only hold strings.

Change it to a List<IContent> and it will work fine.

Also, C#is not Java; do not declare your list variables a IList.
Had you declared them as their actual types (List<string> and whatever CreateDataSource returns), you wouldn't have had this issue.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜