c# - group items by range of values using linq (IGrouping) -
say have list of person
class
public class person { public int age { get; set; } public string name { get; set; } }
how can grouping dynamic ranges? (for illustration starting youngest person grouping ranges of 5 if youngest person 12 groups 12-17, 18-23 ....)
how can determine key
of igrouping
interface? (set key
of each grouping ages average in grouping example)
to key grouping can create function:
string getageinterval(int32 age, int32 minimumage, int32 intervalsize) { var grouping = (age - minimumage)/intervalsize; var startage = group*intervalsize + minimumage; var endage = startage + intervalsize - 1; homecoming string.format("{0}-{1}", startage, endage); }
assuming minimum age 12 , interval size 5 ages between 12 , 16 (inclusive) function homecoming string 12-16
, ages between 17 , 21 (inclusive) function homecoming string 17-21
etc. or can utilize interval size of 6 intervals 12-17, 18-23 etc.
you can create groups:
var minimumage = persons.min(person => person.age); var personsbyageintervals = persons .groupby(person => getageinterval(person.age, minimumage, 5));
to average age in each grouping can this:
var groups = personsbyageintervals.select( grouping => new { ageinterval = grouping.key, averageage = grouping.average(person => person.age), persons = grouping.tolist() } );
this create sequence of groups represented anonymous type properties ageinterval
, averageage
, persons
.
c# linq grouping
No comments:
Post a Comment