Find an item in a list box, C #

I have a list of lists as shown below:

List<List <T> > userList

Class T { string uniqueidentifier, string param2, int param2}

I have a unique identifier, and I need to find the T element in the list that has the same "uniqueidentifier" value.

I can do this using two foreach loops. It doesn't seem so good. I suppose there should be a built-in method, such as Find, which does the same and is highly optimized.

+4
source share
5 answers

Find is not optimized at all - it performs a linear search, since this is the only thing that makes sense in an unsorted list. If you are looking for a more convenient way to write, you can use LINQ:

 var element = (from sublist in userList from item in sublist where item.uniqueidentifier == someid select item).FirstOrDefault(); 
+11
source

Without indexing / hashing, a highly optimized find will not help. It’s best to change the way you store your data, such as a tree.

Without changing the storage mechanism, if you use a multi-core system, parallelize the search.

+2
source

Try the following:

 var query = from ts in userList from t in ts where t.uniqueidentifier == uniqueidentifier select t; var user = query.FirstOrDefault(); 
+1
source

I suggest you change the external list to Dictionary , then you can find the internal list with its unique identifier.

  Dictionary<string, List<T>> myDictionary = new Dictionary<string,List<T>>(); myDictionary["1"] = innerList; List<T> list = myDictionary["1"]; //find list with unique id "1" 
+1
source

not 100% if this will work.

 var match = userList.Where(x=> x.Any(y=>y.uniqueidentifier = "blah")); 
0
source

Source: https://habr.com/ru/post/1333919/


All Articles