Matthew The Terrible
Matthew The Terrible

Reputation: 1643

c# SortedSet how to get an element out

I am pretty new to this so forgive my noobishness here.

I am trying to edit an item in a c# sortedset if I find that the item exists. So I can use list.contains(value) and find that the value does exist in the list. But how do I get that item out of the list. Here is what I have. This gets really slow as my list size gets really big, so I'm guessing there must be a better way than this.

if (list.Contains(p))
{
     Person exists = list.First(person => person.Name.Equals(line[0]));
     // do something here to exists
}
else
{
    // just add the person to the list
}

Upvotes: 5

Views: 10007

Answers (4)

Jordan
Jordan

Reputation: 625

For the .NET Frameworks older than the version 4.7.2:

It is not possible to get an element from SortedSet or HashSet collections (using the Contains method or somehow else). One can just get to know whether the collection contains the element. Since in order to find this element in the collection, one already uses this element (passing it to the Contains method), it can be assumed that one already has this element.

For the .NET Frameworks starting from the version 4.7.2:

See this answer.

Upvotes: 2

ulatekh
ulatekh

Reputation: 1490

You may want to consider using the PowerCollections project — it has a lot of useful improvements to the standard generic collections.

Upvotes: 0

Oleksa
Oleksa

Reputation: 101

As of .NET Framework 4.7.2 there is TryGetValue method available for SortedSet.

Upvotes: 3

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56172

Do you really need SortedSet which is red-black tree? If you don't need sorting, you shouldn't use it. Have you considered HashSet or Dictionary instead which is more suitable (fast) for getting item by key?

In your case you probably need to create Dictionary instance with key equals to person name, i.e.:

Dictionary<string, Person> list;

Then you can get person by it's name, complexity is O(1)

if(list.ContainsKey(line[0]))
{
    list[line[0]]...
}

or even better:

Person p;

if(list.TryGetValue(line[0], out p))
{
    p...
)

Upvotes: 1

Related Questions