Somehow this code looks messy to me:

 var results = query.GroupBy(x => x.ProductStatusId == ProductStatus.Sold || x.ProductStatusId == ProductStatus.OnHold ? "Delivered" :
                                x.ProductStatusId == ProductStatus.Shiped ? "Shiped" :
                                x.ProductStatusId == ProductStatus.NotAvailable ? "NotAvailable" :
                                x.ProductStatusId == ProductStatus.Paid ? "Paid" : "New").Where(g => g.Key != "New")

Is it possible to extract this ternary operator in independent statement.



  • \$\begingroup\$ How about switch case or the new switch expression? \$\endgroup\$ – momt99 Nov 1 '19 at 14:57

Another alternative to the switch statement suggested by jakubiszon is a dictionary:

var statusMap = new Dictionary<ProductStatus, string>
    [ProductStatus.Sold]            = "Delivered",
    [ProductStatus.OnHold]          = "Delivered",
    [ProductStatus.Shiped]          = "Shiped",
    [ProductStatus.NotAvailable]    = "NotAvailable",
    [ProductStatus.Paid]            = "Paid",

var results = query
                .Where(i => statusMap.ContainsKey(i.ProductStatusId)
                .GroupBy(x => statusMap[i.ProductStatusId]);

You could do query.GroupBy(MyTernaryWrapperMethod) and declare that method as

string MyTernaryWrapperMethod(xVariableType x)
    if(x.ProductStatusId == ProductStatus.Sold || x.ProductStatusId == ProductStatus.OnHold) return "Delivered";

    if(x.ProductStatusId == ProductStatus.Shiped) return "Shiped";

    if(x.ProductStatusId == ProductStatus.NotAvailable) return "NotAvailable";

    if(x.ProductStatusId == ProductStatus.Paid) return "Paid";

    return "New"

But, that method seems to return something being an actual property of x. So maybe you should add a new method to x's type. Also it would be better to use swicth/case instead of those ifs:

public string ProductStatusName()
    switch (ProductStatusId)
        case ProductStatus.Sold:
        case ProductStatus.OnHold: return "Delivered";
        case ProductStatus.Shiped: return "Shiped";
        case ProductStatus.NotAvailable: return "NotAvailable";
        case ProductStatus.Paid: return "Paid";
        default: return "New"

And then you do:

var results = query.GroupBy(x => x.ProductStatusName()).Where(g => g.Key != "New")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.