1

I have an object with two different variables inside.

Looks like: ModelB.Text and ModelB.Value and ModelB.Attr

I also have a list of this object and I am loading this List<ModelB> with the data like this:

ModelB.Text = "Car";
ModelB.Value = "345.23";
ModelB.Text = "Car";
ModelB.Value = "343.23";
ModelB.Text = "Car";
ModelB.Value = "323.23";
ModelB.Text = "Toy";
ModelB.Value = "45.23";
ModelB.Text = "Toy";
ModelB.Value = "45.22";
ModelB.Text = "Toy";
ModelB.Value = "45.43";

What I want to do is to find the maximum an minimum valued cars, toys, etc. and check them like ModelB.Attr = "max"; or ModelB.Attr = "min";

So we have to mark the max an min of the each type of object. And yes all the data is string unfortunately and I am parsing it to decimal usually.

4

2 回答 2

3
foreach(var g in models.GroupBy(m => m.Text)
                       .Select(g => g.OrderBy(m => Decimal.Parse(m.Value)))
{
    g.First().Attr = "min";
    g.Last().Attr = "max";
}

如果某种类型(例如汽车)只有一项,则将其标记为"max"。如果要将其标记为"min",则更改应用属性的顺序。

此外,如果并非所有项目在属性中都有正确的十进制值Value,那么您可以添加过滤。

于 2012-12-13T10:16:18.807 回答
0

好吧,我不会在这里为解析错误、文化等问题烦恼:这些是业务问题,而不是 linq 问题。

如果多个对象具有相同的最大值,我也不知道该怎么办:全部标记或不标记,所以我标记第一个。要将它们全部标记,请将 First 替换为 ForEach

foreach(var grp in myList.GroupBy(o => o.Text))
    grp.First(g => decimal.parse(g.Value) == grp.Max(o => decimal.Parse(o.Value)).Attr="max";

编辑:这是 foreach 实现

foreach(var grp in myList.GroupBy(o => o.Text))
{
    string min = grp.Min(o => decimal.Parse(o.Value));
    string max = grp.Max(o => decimal.Parse(o.Value));
    foreach(var obj in grp.Where(o => o.Value == min)
        obj.Attr="min";
    foreach(var obj in grp.Where(o => o.Value == max)
        obj.Attr="max";
}
于 2012-12-13T10:11:11.967 回答