Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我的Linq或Lambda表达式的优化方式_C#_Linq_Lambda - Fatal编程技术网

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

C# 我的Linq或Lambda表达式的优化方式,c#,linq,lambda,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.C

我有一个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();
有什么方法可以用一个表达式得到这个结果吗?

您可以使用:

您需要一个新的
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);
    }
}
公共类CurrencyCodeComparer:IComparer
{
公共整数比较(字符串x、字符串y)
{
如果(x==y)
返回0;
如果(x=“美元”)
返回-1;
如果(y=“美元”)
返回1;
返回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();
附言:
说实话,扩展方法的名称是
Distinct
。但是,我认为您可以使用自己的扩展方法


这是小提琴:

它以升序显示所有东西。但我希望美元先按升序显示,然后再按升序显示其他。然后用
.OrderBy(c=>c.CurrencyCode!=“USD”)
替换
.OrderBy(c=>c.CurrencyCode==“USD”)
@SabyasachiMishra您能告诉我,如果出现这种情况,会有什么结果吗:
“欧元”,“美元”、“AZN”、“卢布”
@SabyasachiMishra在我的情况下,结果将是:
美元、AZN、欧元、卢布
“美元”、“AZN”、“欧元”、“卢布”
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();