2009-06-16 3 views
5

私はCountryという名前のクラスを持っています。それには、パブリックメンバー 'CountryName'と 'States'があります。リストのSequenceEqualを動作させます

私は国のリストを宣言しました。

今、新しい '国'を受け入れ、CountryListに既に '国'があるかどうかを判断する関数を記述したいと思います。

私はアメリカのCOUNTRYNAMEプロパティを使用して状態を比較したいと私は

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

のような機能を書いてみました、私はSequenceEqual作品は状態のCOUNTRYNAMEに基づくように、私の機能を変更したいですか?

答えて

12

多くの単純なクエリに分解し、これらのクエリをまとめて戻します。

は、名前で一致する項目の順序を作ることから始めレッツ:

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(); 

これはそのまま動作するはずです。しかし、あなたが本当にバフになりたい場合、あなたは1つの大きなクエリですべてを書くことができます!

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(); 

これで完了です。やさしい!ちょっと覚えて、小さなステップに分割し、個々の問題を個別に解決してから、小さな結果からソリューションをまとめてください。

+2

これはC#-teamの誰かが読んでいる間に書かれているのか本当に疑問に思っています。エリック・リッパートはもちろんC#-teamです! – usr

1

ItemでIComparerを実装しましたか?

1

私が正しく理解していれば、最初に2つのアイテムの名前を確認してから各サブアイテムの名前を順番に確認する2つのアイテムを比較する方法が必要です。あなたが望むものは次のとおりです:

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; 
    } 
関連する問題