まず、比較したいことを言います: My Custom Object (Item) has List of strings taxids
. あるリスト内のすべての文字列が別の文字列リストに含まれているかどうかを確認したい (taxids
別のオブジェクト (アイテム) の別のリストにもなる)。
だから、これはクラスです:
public class Item
{
public long taxid { get; set; }
public long contentid { get; set; }
public string taxname { get; set; }
public IEnumerable<string> taxids { get; set; }
}
次に、これらはダミーのカスタム オブジェクトです。
List<string> numbers = new List<string> { "5", "1" };
List<string> numbers2 = new List<string> { "1", "2", "5","3","564" };
Item pr = new Item();
pr.contentid = 2517;
pr.taxid = 2246;
pr.taxids = numbers.AsEnumerable();
pr.taxname = "nameItem1";
List<Item> te = new List<Item>();
te.Add(pr);
IQueryable<Item> er = te.AsQueryable();
Item pr2 = new Item();
pr2.contentid = 0;
pr2.taxid = 0;
pr2.taxids = numbers2.AsEnumerable();
pr2.taxname = "nameItem2";
List<Item> te2 = new List<Item>();
te2.Add(pr2);
IQueryable<Item> er2 = te2.AsQueryable();
IQueryable<Item> both = er.Intersect(er2, new ItemComparer());
ここでは、カスタムの comparer を使用しますItemComparer
。このコードは次のとおりです。
public class ItemComparer : IEqualityComparer<Item>
{
// items are equal if their names and item numbers are equal.
public bool Equals(Item x, Item y)
{
//Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
//Check whether the items' properties are equal.
return x.taxids.Intersect(y.taxids).SequenceEqual(x.taxids);
}
// If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects.
public int GetHashCode(Item item)
{
//Check whether the object is null
if (Object.ReferenceEquals(item, null)) return 0;
//Get hash code for the Name field if it is not null.
int hashItemName = item.taxids == null ? 0 : item.taxids.GetHashCode();
//Calculate the hash code for the item.
return item.taxids.GetHashCode();
//return "a".GetHashCode();
}
}
問題は、変数both
が taxid フィールドに何もないことです。通常、「5」「1」のリストが必要です。
比較するときに hashCode が同じでなければならないことはわかっています。しかしtaxids
、同じになることはありません。別の文字列リストで文字列を探すからです。
誰でもこの問題についてさらに助けてもらえますか?
(また、小さな質問: => のようなすべてのものに対して常に同じハッシュコードを返す場合、"a".GetHashCode()
これは機能するかどうか?
前もって感謝します