开发者

Is there a more effecient way to determine if two EntityCollections contain the same elements?

I need to determine if two EntityCollections are equal. I have code I think will do the trick, but I'm wondering if there might be a more effecient algorithm? Note, the EntityCollections will likely have less than 10 elements each.

    private static bool isEquivalent(
        EntityCollection<MyClassDetails> myClassDetails1,
        EntityCollection<MyClassDetails> myClassDetails2 )
    {
        var myClassComparer = new MyClassComparer();

        return
            myClassDetails1.All(
                myClassDetail1 =>
                 myClassDetails2.Contains(
                    myClassDetail1, myClassComparer ) );
    }

    class MyClassComparer : IEqualityComparer<MyClassDetails>
    {
        public bool Equals( MyClassDetails details1, MyClassDetails details2 )
        {
            return details1.DetailID == detail开发者_Python百科s2.DetailID;
        }

        public int GetHashCode( MyClassDetails obj )
        {
            return obj.GetHashCode();
        }
    }


Well to start with, if your collections will likely only hold 10 elements each then it's probably premature to be worrying about efficiency of this algorithm, unless you're calling it a lot in a critical path. But one thing you could try is to use the Intersects and Any extensions instead.

return !myClassDetails1.Intersects(myClassDetails2, new MyClassComparer()).Any();

I'm not sure how much more efficient it would be but the code would be prettier. Also, in the past I have created an FuncComparer for just such an occasion.

class FuncComparer<T> : IEqualityComparer<T>
{
  private Func<bool, T, T> compare;
  public FuncComparer(Func<boo, T, T> compare){
    this.compare = compare;
  }
  public bool Equals(T left, T right) {
    return this.compare(left, right);
  }
}

// usage
return !items1
  .Intersects(items2, new FuncComparer<Item>((l, r) => l.Id == r.Id))
  .Any();


I'm pretty sure you'll be traversing the array each time through your main loop (.All). If you used linq to sort them (orderby) you could then just loop through one list and compare the item to the item at the same index in the other list. In fact you could return false as soon as you hit a difference.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜