Question

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
}
Was it helpful?

Solution 3

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...
)

OTHER TIPS

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

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top