c# - Order a collection by type with specific counting -
not quite sure how explain this, here's try:
on webpage need show references , quotes in 1 list. first need show 4 references (image, title, link), 1 quote (quote, author) , 1 time again 4 references, 1 quote , on.
i have records coming 2 different sources. 1 called references , other called quotes. within big collection hold both of sources.
now need find way them sorted sequence:
reference 1 reference 2 reference 3 reference 4 quote 1 reference 5 reference 6 reference 7 reference 8 quote 2makes sense?
this code of specific referenceitem class, 1 utilize create collection both datasources in it.
public class referenceitem { public referencetype referencetype { get; set; } public string title { get; set; } public string summary { get; set; } public string imageurl { get; set; } public string pageurl { get; set; } public string referent { get; set; } public int counter { get; set; } }
any ideas on how sort this?
you utilize lookup
both reference-types similar dictionary rather efficient. utilize for
-loop , enumerable.skip
/take
create packages each sequence , enumerable.concat
set them together. add together them new list<referenceitem>
:
var lookup = items.tolookup(i => i.referencetype); var sorteditems = new list<referenceitem>(items.count); (int refix = 0, quoteix = 0; refix < items.count; refix += 4, quoteix++) { var refpackage = lookup[referencetype.references].skip(refix).take(4); var quotepackage = lookup[referencetype.quotes].skip(quoteix).take(1); sorteditems.addrange(refpackage.concat(quotepackage)); }
here sample i've used testing:
var items = new list<referenceitem>() { new referenceitem{ referencetype = referencetype.quotes, counter = 1 }, new referenceitem{ referencetype = referencetype.references, counter = 2 }, new referenceitem{ referencetype = referencetype.quotes, counter = 3 }, new referenceitem{ referencetype = referencetype.references, counter = 4 }, new referenceitem{ referencetype = referencetype.references, counter = 5 }, new referenceitem{ referencetype = referencetype.references, counter = 6 }, new referenceitem{ referencetype = referencetype.references, counter = 7 }, new referenceitem{ referencetype = referencetype.references, counter = 8 }, new referenceitem{ referencetype = referencetype.references, counter = 9 }, new referenceitem{ referencetype = referencetype.references, counter = 10 } };
c# asp.net linq
No comments:
Post a Comment