Find an element in List of List, c#
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();
not 100% if this will work..
var match = userList.Where(x=> x.Any(y=>y.uniqueidentifier = "blah"));
精彩评论