当前位置: 动力学知识库 > 问答 > 编程问答 >

Fastest search of a collection of objects by specifying a property of an object in .NET

问题描述:

I'd like to have a Collection that is searchable by the value of a Property in T. The Property will likely change many times over the life of an instance of T. The speed of the search is important - linear search is out of the question.

I've successfully used a separate instance of Dictionary, but maintaining another Collection this seems like a kluge. I hope there is a better way.

One possibility is to use SortedSet class which can keep my Objects sorted ordered by Property. I can copy the SortSet to an Array and use Array.BinarySearch, but I cannot accept the overhead of creating this array each time I want to search. Maybe there is some way to use BinarySearch on a SortedSet?

I admit I have seen this question with some answers at least twice, but I could not figure a clear alternative to my Dictionary approach.

I'm using .Net 4.0.

网友答案:

Would something like this work for you? Of course you can change the underlying set to be something other than a list, and I'm not guaranteeing it works as I wrote it, but the idea is there to keep the list constantly updated.

public class Holder
{
    public Action OnPropChange;

    int _prop;
    public int Prop
    {
        get
        {
            return _prop;
        }
        set
        {
            _prop = value;
            OnPropChange();
        }
    }
}

public class SortedListThing : List<Holder>
{
    public void Add(Holder h)
    {
        BinarySortedInsert(h);
        h.OnPropChange = () => { this.Remove(h); base.Add(h); };
    }

    private void BinarySortedInsert(Holder h)
    {
        //do stuff
    }

    public void Remove(Holder h)
    {
        h.OnPropChange = null;
        base.Remove(h);
    }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: