Reputation: 1172
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();
Upvotes: 10
Views: 12322
Reputation: 117037
LINQ and ANSI queries only have passing similarities. There should be very little expectation that any of the ANSI syntax crosses over to LINQ.
UNION
is no exception.
Here are my three preferred options:
(1)
var strings =
Enumerable
.Union(
from MemberInfo member in Whitelist.Members
select member.ToString(),
from Type type in Whitelist.Types
select type.ToString());
(2)
var members =
from MemberInfo member in Whitelist.Members
select member.ToString();
var types =
from Type type in Whitelist.Types
select type.ToString()
var strings = Enumerable.Union(members, types);
(3)
var strings =
(
from MemberInfo member in Whitelist.Members
select member.ToString()
).Union(
from Type type in Whitelist.Types
select type.ToString()
);
I like these options as they help to clearly show that a Union
is being performed.
Upvotes: 5
Reputation: 81493
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
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();
Upvotes: 8
Reputation: 42
You need to use Union
method. Like that.
var strings = (from MemberInfo member in Whitelist.Members
select member.ToString())
.Union(
from Type type in Whitelist.Types
select type.ToString());
Upvotes: 1