c# - 联合在 LINQ 查询语法中可用吗?

标签 c# linq

我注意到我无法使用两个选择的 union 构建 linq 查询,使用 ANSI syntax .

.net 文档有一篇关于 query syntax examples 的文章未显示联合的地方。然而,在.net examples for method syntax下, 给出了并集的例子。

我知道我可以结合查询语法选择和基于方法的选择来绕过这个问题,但我很好奇我是否可以完全不用基于方法的语法。

var strings =
          from MemberInfo member in Whitelist.Members
          select member.ToString()
          union
          from Type type in Whitelist.Types
          select type.ToString();

最佳答案

答案是否定的。尽管您可以在查询语法中做很多事情,但它缺少一些基本操作(如您所见)。您将不得不使用扩展方法。

给定

Query Keywords (C# Reference)


Enumerable.Union Method (IEnumerable, IEnumerable)

Produces the set union of two sequences by using the default equality comparer.

示例

ProductA[] store1 = { new ProductA { Name = "apple", Code = 9 }, 
                       new ProductA { Name = "orange", Code = 4 } };

ProductA[] store2 = { new ProductA { Name = "apple", Code = 9 }, 
                       new ProductA { Name = "lemon", Code = 12 } };

var union = store1.Union(store2);

var union =
     (from MemberInfo member in Whitelist.Members select member.ToString()).Union
     (from Type type in Whitelist.Types select type.ToString());

或等效

var union =
    (from MemberInfo member in Whitelist.Members select member.ToString()).Concat
    (from Type type in Whitelist.Types select type.ToString()).Distinct();

关于c# - 联合在 LINQ 查询语法中可用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50867644/

相关文章:

c# - 如何通过隐藏编码将文本 block 放入滚动查看器中? (wpf)

c# - 如何将特定数据从一个 View 传输到另一个 View

linq - IronPython 的表达式树

c# - LINQ WHERE 语句/忽略条件

Java/Android C# linq 的最佳等价物

c# - 每 10% 输入一个代码分支,直到 100%

c# - 在 C# 中针对现有文件的 CreateNew 的 FileStream 构造函数抛出异常

c# - 将 XML 发布到 REST 时出现 HTTP 401 错误

c# - 通用 LINQ orderby lambda 函数

c# - LINQ 查询不返回任何行