I have a list of lists as below:
List<List <T> > userList
Class T { string uniqueidentifier, string param2, int param2}
I have a uniqueidentifier and i need to find the element T in the list that has the same 'uniqueidentifier' value.
I can do it using two 'foreach' loops. This does not seem to be nice way doing things. I guess there should be some inbuilt method like 'Find' that does the same thing and is highly optimized.
Find
is not optimized at all -- it performs a linear search, since that's the only thing that makes sense on an unsorted list. If you are looking at a nicer way to write it, you could use LINQ:
var element = (from sublist in userList
from item in sublist
where item.uniqueidentifier == someid
select item).FirstOrDefault();
Without indexing/hashing a "highly optimized" find won't help. Your best bet is change the storage method of your data, such as a tree.
Without changing the storage mechanism, if you are on a multi-core system parallelize the search.
I would suggest you change the outer list to a Dictionary, then you can find the inner 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"
Try this:
var query =
from ts in userList
from t in ts
where t.uniqueidentifier == uniqueidentifier
select t;
var user = query.FirstOrDefault();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With