LINQ Group By with Replace

时间:2017-10-26 16:13:05

标签: sql-server linq

假设我有一个像这样的表:

ColumnA    ColumnB
-------    -------
Used       Citroen
Km0        BMW
New        BMW
Used       Peugeot
Used       Volvo

在LINQ中,我将提取COlumnA的所有不同值,但在结果中我会将“Used”和“Km0”分组在相同的值下: 所以结果将是:

Used -> 4 cars
New -> 1 car

2 个答案:

答案 0 :(得分:1)

如果您有特定值要与组中的其他项“捆绑”,则可以使用条件表达式:

var res = cars
    .GroupBy(c => c.ColumnA == "Km0" ? "Used" : c.ColumnA)
    .ToDictionary(g => g.Key, g => g.Count);

答案 1 :(得分:0)

考虑创建一个EqualityComparer,比较两个ColumnA类型的相等性,如果一个是Used而另一个是Km0,则返回true,

如果你这样做,你可以在你想要Km0作为Used的每个linq语句中使用它,不仅在GroupBy中,而且在ToDictionary中,Where,Distinct等

假设ColumnA是一个字符串。 Microsoft建议从类EqualityComparer

派生相等比较器
class CarColumnAComparer : EqualityComparer<string>
{
    public static IEqualityComparer<string> Comparer
    {
        get{return new CarColumnAComparer();}
    }

    const string used = 'Used';
    const string km0 = "Km0";

    public override bool Equals(string x, string y)
    {
        if (x == null) return y == null; // true if both null, false ix x null, y not null
        if (y==null) return false;       // x is not null, false if y null
        if (Object.ReferenceEquals(x, y) return true;
        if (x.GetType() != y.GetType()) return false; // false if different types

        // declare equal if one is 'Used' and other is 'Km0'
        if (x == used && y == km0) return true;
        else if (x == km) and y == used) return true;
        else return x == y;
    }

    public override int GetHashCode(string x)
    {
         if (x == null) throw new ArgumentNullException(nameof(x));

         // return the same hashCode for x==used and x==km0:
         if (x == km0)
             return used.GetHashCode();
         else
             return x.GetHashCode();
    }

用法:

var result = cars.GroupBy(car => car.ColumnA, carColumnAComparer.Comparer);

var dictionary = new Dictionary<string, Car> CarDictionary(carColumnAComparer.Comparer);
var disinctValues = cars.Distinct(carColumnAComparer.Comparer);