简体   繁体   中英

C# Structure that sorts key pairs and is accessible?

Noob here. I've been scouring the internet for days, and cannot find a decent structure that auto-sorts data (like SortedSet), while still allowing that data to be accessible (like List). Here's what I have:

A list containing 100,000 nodes, added and modified regularly.

List<Nodes> nodes;

The node object, containing data I need to access/change

public class Node (string name, int index){ doSomething(); }

I don't wish to be vague, but can't sort the actual list because the index is a history of when nodes were added. Thus, I want to use a structure that auto-sorts KeyValuePair pairs(where string is the name to be sorted by, and int is the index as it is found in my list of nodes), but I must be able to access the value. Here's what I want to do:

// Add a node to the list, then to the structure
int index = nodes.Count;
nodes.Add(new Node("someName", index));
someStructure.Add("someName", index);

// Give name to structure, which returns int value for use in finding node
node[someStructure.findValueOf("someName"))].doSomething();

This would tell the node with the name "someName" to doSomething();

I am positive that I am missing something. I've tried using SortedSet, SortedList, Dictionary, etc. In each case, I can't retrieve the sorted object. What is the purpose of auto-sorting if I can't find out where they are at? Please help my poor life.

You are looking for a SortedDictionary .

As per the documentation: Represents a collection of key/value pairs that are sorted on the key. Although, as some comments say, those 100k objects would be better kept in a database...

Link: https://msdn.microsoft.com/en-us/library/f7fta44c(v=vs.110).aspx

You can use SortedList and LINQ:

SortedList<int,string> list = new SortedList<int, string>();

list.Add(1, "name1");
list.Add(2, "name2");;

var c = list.Select(x => x.Value == "name2").FirstOrDefault();

However I agree with a Christopher's comment about using db.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM