views:

42

answers:

2

I am not sure if CopyMost is the correct term to use here, but it's the term my client used ("CopyMost Data Protocol"). I have a set of data:

Increment    Value
.02            1
.04            1
.06            1
.08            2
.10            2

I need to return which Value occurs the most "CopyMost". In this case, the value is 1. Right now I had planned on writing an Extension Method for IEnumerable to do this for integer values. Is there something built into Linq that already does this easily? Or is it best for me to write an extension method that would look something like this

records.CopyMost(record => record.Value);
+4  A: 

Well, here's one option:

var query = (from item in data
             group 1 by item.Value into g
             orderby g.Count() descending
             select g.Key).First();

Basically we're using GroupBy to group by the value - but all we're interested in for each group is the size of the group and the key (which is the original value). We sort the groups by size, and take the first element (the one with the most elements).

Does that help?

Jon Skeet
It all makes sense, except the 1. "group 1 by item.Value into g". Why 1? Why not item? I tested and they both yield the same result. I know the 1 is probably better for some reason, but I'd like to understand why.
jsmith
@jsmith: Just to indicate that you really don't care about the values within the group. You might even use `(byte) 1` to be more efficient :)
Jon Skeet
@Jon Skeet So what happens if I were to use a different value, say `group 2`?
msarchet
@msarchet: Nothing would change. We don't care about the values in the group, only the group's size. They could be goldfish for all the difference it'll make to the results.
Jon Skeet
@Jon Skeet, gotcha.
msarchet
+2  A: 

Jon beat me to it, but the term you're looking for is Modal Average.

Edit:

If I'm right In thinking that it's modal average you need then the following should do the trick:

var i = (from t in data
         group t by t.Value into aggr
         orderby aggr.Count() descending
         select aggr.Key).First();
mdresser