我的Linq或Lambda表达式的优化方式

时间:2015-08-01 09:51:01

标签: c# linq lambda

我有一个Linq查询,我需要获取所有不同的货币代码。货币代码USD将首先显示,其余将按字母顺序排序。

我试过这样就把它分成两个这样的查询,它运行正常:

var currencies = context.DbCurrencies.DistinctBy(x => x.CurrencyCode)
                .Where(c => c.CurrencyCode != null).ToList();

var result1 = currencies.First(c => c.CurrencyCode == "USD");

var result2 = currencies.OrderBy(c => c.CurrencyCode)
              .Where(c => c.CurrencyCode != "USD").ToList();

return result1.Concat(result2).ToList();

有什么方法可以用一个表达式来获得它吗?

2 个答案:

答案 0 :(得分:4)

您可以使用custom comparer

return context.DbCurrencies.DistinctBy(x => x.CurrencyCode)
    .Where(c => c.CurrencyCode != null).OrderBy(c => c.CurrencyCode, new CurrencyCodeComparer()).ToList();

您需要一个新的CurrencyCodeComparer课程,但您可以重复使用它:

public class CurrencyCodeComparer : IComparer<string>
{
    public int Compare(string x, string y)
    {
        if (x == y)
            return 0;
        if (x == "USD")
            return -1;
        if (y == "USD")
            return 1;
        return x.CompareTo(y);
    }
}

答案 1 :(得分:3)

您可以尝试:

var currencies = context.DbCurrencies
        .DistinctBy(x => x.CurrencyCode)
        .Where(c => c.CurrencyCode != null) // add filter to query
        .AsEnumerable() // execute query against database
        .OrderBy(c => c.CurrencyCode != "USD") // Move USD to the top of the list
        .ThenBy(c => c.CurrencyCode) // Then order by currency codes
        .ToList();

P.S:说实话,扩展名mehtod的名字是Distinct。但是,我认为你可以使用自己的扩展方法。

这是小提琴:https://dotnetfiddle.net/ipgWUJ

相关问题