优化的方式为我的Linq或Lambda表达式
本文关键字:Lambda 表达式 Linq 我的 方式 优化 | 更新日期: 2023-09-27 18:05:55
我有一个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();
是否有任何方法,我可以得到这个与一个单一的表达式?
您可以使用自定义比较器:
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);
}
}
您可以尝试:
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:
说实话,扩展方法的名字是Distinct
。但是,我认为您可以使用自己的扩展方法。
这里是小提琴:https://dotnetfiddle.net/ipgWUJ