Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is union available in LINQ query syntax?

Tags:

c#

linq

I noticed that I was unable to structure a linq query with a union of two selects, using ANSI syntax.

The .net documentation has an article on query syntax examples where union is not shown. However, under .net examples for method syntax, a union example is given.

I know I can combine query syntax selects and Method based selects to bypass this problem, but I am curious if I can do entirely without method based syntax.

var strings =
          from MemberInfo member in Whitelist.Members
          select member.ToString()
          union
          from Type type in Whitelist.Types
          select type.ToString();
like image 824
dcdgo Avatar asked Jun 15 '18 00:06

dcdgo


1 Answers

The answer is no. As much as you can do in query syntax, it lacks some basic operations (as you have seen). You will have to use the extension methods.

Given

Query Keywords (C# Reference)


Enumerable.Union Method (IEnumerable, IEnumerable)

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

Example

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);

or

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

or equivalent

var union =
    (from MemberInfo member in Whitelist.Members select member.ToString()).Concat
    (from Type type in Whitelist.Types select type.ToString()).Distinct();
like image 189
TheGeneral Avatar answered Oct 24 '22 16:10

TheGeneral