c# - Items Common to Most Lists -
given list of lists (let's 5 lists, have real number work), can find items common 5 lists relative ease (see intersection of multiple lists ienumerable.intersect()) using variation of following code:
var list1 = new list<int>() { 1, 2, 3 }; var list2 = new list<int>() { 2, 3, 4 }; var list3 = new list<int>() { 3, 4, 5 }; var listoflists = new list<list<int>>() { list1, list2, list3 }; var intersection = listoflists.aggregate((previouslist, nextlist) => previouslist.intersect(nextlist).tolist());
now let's intersection
ends containing 0 items. it's quite possible there objects common 4/5 lists. how go finding them in efficient way?
i know run through combinations of 4 lists , save results, method doesn't scale (this have done on approx. 40 lists).
if no item common 4 lists, search repeated looking items common 3/5 lists, etc. visually, represented lists of grid points , we're searching points have overlap.
any ideas?
edit: maybe better @ each point , keep track of how many times appears in each list, create list of points highest occurrence?
you can select numbers (points) lists, , group them value. sort result group size (i.e. lists count point present) , select common item:
var mostcommon = listoflists.selectmany(l => l) .groupby(i => i) .orderbydescending(g => g.count()) .select(g => g.key) .first(); // outputs 3
instead of taking first item, can take several top items replacing first()
take(n)
.
returning items number of lists (ordered number of lists):
var mostcommonitems = l in listoflists in l group g orderby g.count() descending select new { item = g.key, numberoflists = g.count() };
usage (item strongly-typed anonymous object):
var topitem = mostcommonitems.first(); var item = topitem.item; var listscount = topitem.numberoflists; foreach(var item in mostcommonitems.take(3)) // iterate on top 3 items
Comments
Post a Comment