Let SequenceEqual Work for List

I have a class called Country. He has community members, "CountryName" and "States."

I have announced a list of countries.

Now I want to write a function that accepts a new "country" and decides whether the CountryList already has a "country".

I tried to write a function like

bool CheckCountry(Country c)
{
    return CountryList.Exists(p => p.CountryName == c.Name
                                && p.States.SequenceEqual(c.States));
}

How do I want to compare states using the CountryName property for the States, I want to change my function so that SequenceEqual works based on the CountryName states?

+5
source share
3 answers

Divide it into many simple queries, and then put these queries together.

Let's start by creating a sequence of elements that match by name:

var nameMatches = from item in itemList where item.Name == p.Name select item;

p. ? :

var pnames = from subitem in p.SubItems select subitem.Name;

nameMatches, . ? , , pnames, :

var matches = from item in nameMatches
              let subitemNames = 
                  (from subitem in item.SubItems select subitem.Name)
              where pnames.SequenceEqual(subitemNames)
              select item;

, - ?

return matches.Any();

, . , !

return (
    from item in itemList
    let pnames = 
        (from psubitem in p.SubItems select psubitem.Name)
    let subitemNames = 
        (from subitem in item.SubItems select subitem.Name)
    where item.Name == p.Name
    where pnames.SequenceEqual(subitemNames)
    select item).Any();

. ! , , , .

+12

IComparer Item?

+1

If I understand you correctly, you want to compare two elements in which you first check the name of the two elements, and then sequentially check each sub-element name. Here is what you want:

    public override bool Equals(object obj)
    {
        return this.Name == (obj as Item).Name;
    }
    public override int GetHashCode()
    {
        return this.Name.GetHashCode();
    }
    public bool Check(Item obj)
    {
        if (this.Name != obj.Name)
            return false;
        //if the lists arent of the same length then they 
        //obviously dont contain the same items, and besides 
        //there would be an exception on the next check
        if (this.SubItems.Count != obj.SubItems.Count)
            return false;
        for (int i = 0; i < this.SubItems.Count; i++)
            if (this.SubItems[i] != obj.SubItems[i])
                return false;
        return true;
    }
+1
source

All Articles