开发者

Can't find index of an Item on a List on Silverlight

I have a list of items of type Country and I'm trying to find the index of and sp开发者_如何学Goecific Country on the list but the IndexOf() method always returns -1.

The Country object look like this:

    public class Country
    {
        public string CountryCode { get; set; }
        public string CountryName { get; set; }
    }

Then when I try to use the IndexOf() method I do the next:

var newcountry = new Country
                     {
                         CountryCode = "VE",
                         CountryName = "VENEZUELA"
                     };
        var countries = ListBoxCountries.Items.Cast<Country>().ToList();

        if (countries.IndexOf(newcountry) == -1)
            countries.Add(newcountry);

Lets assume I have an already filled list with with the countries and "Venezuela" is on the list, the IndexOf() method never find the country.

EDIT:

So I got a little help from ReSharper here and he made this once I told him to override the Equals() method:

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != typeof (Country)) return false;
            return Equals((Country) obj);
        }

        public bool Equals(Country other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return Equals(other.CountryCode, CountryCode) && Equals(other.CountryName, CountryName);
        }

        public override int GetHashCode()
        {
            unchecked
            {
                return ((CountryCode != null ? CountryCode.GetHashCode() : 0)*397) ^ (CountryName != null ? CountryName.GetHashCode() : 0);
            }
        }

And here comes another question: It's ok to do all this just to compare two objects?


I suspect this is due to a reference issue. You'll need to override the Equals(); method in your Country class to check.

I'd use code like this:

public bool Equals(Country other)
{
    return this.CountryName.Equals(other.CountryName);
}


That's because IndexOf uses reference equality for comparing objects

You can use this

var newcountry = new Country
                 {
                     CountryCode = "VE",
                     CountryName = "VENEZUELA"
                 };


bool country = ListBoxCountries.Items.Cast<Country>().FirstOrDefault(c=>c.CountryCode == newcountry.CountryCode && c.CountryName == newcountry.CountryName)

if(country == null)
  countries.Add(newcountry);

Or you can better ovverride Equals() method to compare objects.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜