gpt4 book ai didi

c# - 默认后不能出现linq过滤器?

转载 作者:太空宇宙 更新时间:2023-11-03 23:14:32 25 4
gpt4 key购买 nike

我一直试图在 LINQ 中重写一些命令式代码,直到我意识到我遗漏了什么。但我不知道为什么这是一个问题。考虑以下。使用

运行 Test.Test2(testList) 时测试失败

Sequence contains no matching elements

过去,我交替处理这些形式,通过将我的谓词推送到 FirstSingle 等...子句来编写更小的代码。显然,当涉及到 DeafultIfEmpty 时,我不能这样做。这是因为 WhereFirstSingle 等不能互换吗?或者,是因为 DefaultIfEmpty 子句引入了复杂性吗?

编辑 1我添加了一个测试来表明 FirstOrDefault 不起作用。它因“未找到”不等于 (null) 而失败。

public static class Test
{
public static string Test1(params string[] input)
{
return input
.Where(x => x == "apples")
.DefaultIfEmpty("bannanas")
.First();
}

public static string Test2(params string[] input)
{
return input
.DefaultIfEmpty("bannanas")
.First(x => x == "apples");
}

public static string Test3(params string[] input)
{
return input
.DefaultIfEmpty("bannanas")
.FirstOrDefault(x => x == "apples");
}
}

public class TestStuff
{
[Fact]
public static void TestOneAndTwo()
{
var testList = new string[] { "oranges", "pears", "pineapples" };
var one = Test.Test1(testList);
var two = Test.Test2(testList);
Assert.Equal(one, two);
}

[Fact]
public static void TestOneAndThree()
{
var testList = new string[] { "oranges", "pears", "pineapples" };
var one = Test.Test1(testList);
var three = Test.Test3(testList);
Assert.Equal(one, three);
}
}

最佳答案

LINQ 方法的顺序很重要,考虑每个方法对输入可枚举的作用({ "oranges", "pears", "pineapples"}):

public static string Test1(params string[] input)
{
return input
.Where(x => x == "apples") // empty enumerable, because no item matches "apples"
.DefaultIfEmpty("not found") // {"not found"}, since the enumerable is empty
.First(); //"not found", since we have this item
}

public static string Test2(params string[] input)
{
return input
.DefaultIfEmpty("not found") // { "oranges", "pears", "pineapples" }
//i.e., nothing changes, because input is not empty
.First(x => x == "apples"); //Exception because there is no
//item that is equal to "apples"
}

如果将最后一个方法从 First 更改为 FirstOrDefault,那将产生 null 因为 default(string)null

关于c# - 默认后不能出现linq过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37710390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com