C#的SortedSet如何获得一个元素了如何获得、元素、SortedSet

2023-09-05 23:51:00 作者:善恶终有报

我是pretty的新的这个所以这里原谅我的noobishness。

我想编辑交流#SortedSet的一个项目,如果我发现该项目存在。所以,我可以使用list.contains(值),并发现价值确实存在在列表中。但我怎么拿到项目淘汰之列。下面是我。这得到我的列表的大小变得非常大的很慢,所以我猜肯定有比这更好的办法。

 如果(list.Contains(P))
{
     人的存在= list.First(人=> person.Name.Equals(行[0]));
     //做一些事情在这里存在
}
其他
{
    //只是人添加到列表
}
 

解决方案

你真的需要的SortedSet 这是红黑树?如果您不需要排序,你不应该使用它。你是否考虑过的HashSet 词典而不是哪一种更适合(快)获取项目通过按键?

在你的情况,你可能需要创建词典实例与关键等于人的名字,如:

 词典<字符串,人>清单;
 
redis数据类型 String List Hash Set Sorted Set 简介与命令

然后,你可以通过它的名字得到的人,复杂度为O(1)

 如果(list.ContainsKey(行[0]))
{
    列表[行[0] ...
}
 

甚至更好:

 人物磷;

如果(list.TryGetValue(行[0],出ρ))
{
    p ...
)
 

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
}

解决方案

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