Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find an element in List of List, c#

Tags:

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.

like image 731
Sandy Avatar asked Dec 31 '10 22:12

Sandy


4 Answers

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();
like image 150
cdhowie Avatar answered Oct 13 '22 11:10

cdhowie


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.

like image 24
Andrew T Finnell Avatar answered Oct 13 '22 11:10

Andrew T Finnell


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"
like image 32
BrokenGlass Avatar answered Oct 13 '22 11:10

BrokenGlass


Try this:

var query =
    from ts in userList
    from t in ts
    where t.uniqueidentifier == uniqueidentifier
    select t;

var user = query.FirstOrDefault();
like image 24
Enigmativity Avatar answered Oct 13 '22 12:10

Enigmativity