c# - Group objects in List by property in object that is List using LINQ -
i have list of objects (name of object ngramm) , object has property - list of strings (name of property rawngramwords). there property of rawngramwords - ngramcount - number of objects in list same rawngramwords (the same lists of strings in different ngramm). if there example 3 objects (ngramm) in list same rawngramwords need 1 ngramm object ngramcount property = 3. other 2 objects same rawngramwords lists should deleted list. used code:
public static list<ngramm> countnwordsinngrams(list<ngramm> listofngramms) { list<int> indexesofngramsinlisttodelete = new list<int>(); for(int = 0; < listofngramms.count; i++) { for(int j = i+1; j < listofngramms.count; j++) { bool areequivalent = !listofngramms[i].rawngramwords.except(listofngramms[j].rawngramwords).any(); if(areequivalent == true) { indexesofngramsinlisttodelete.add(i); listofngramms[j].ngramcount = listofngramms[j].ngramcount + listofngramms[i].ngramcount + 1; } } } (int = listofngramms.count; >= 0; i--) { if (indexesofngramsinlisttodelete.contains(i)) { listofngramms.removeat(i); } } return listofngramms; }
the speed of method slow. (it counts ngramcount error - on whole doesn't matter due slow speed - need way find same lists of strings in these objects). - there way use group count objects same list (rawngramwords) linq? thank you
this example group list
of ngramm
objects rawngramwords
property dictionary<string[], list<ngramm>>
.
the key (string[]
) of dictionary rawngramwords
property of ngramm
objects.
assuming ngramm
class looks :
class ngramm { public string[] rawngramwords; public int ngramcount; }
you list<ngramm>
:
list<ngramm> listofngramms; dictionary<string[], list<ngramm>> groupedresults = (from ngramm in listofngramms group ngramm ngramm.rawngramwords groupedngramms select groupedngramms).todictionary(gdc => gdc.key, gdc => gdc.tolist());
on side note, code posted doing few things don't entirely understand reason (re-iterating tail of first iteration example). slowing down.
Comments
Post a Comment