0

I have a class just like the following:

public class ParentData
{
    public List<ChildData> ChildDataList { get; set; }
    public ChildData AnotherChildData { get; set; }
}

I am looking for a simple Linq query to make a selection from these 2 members. Here is what I actually do:

var query = (from data in parentData.ChildDataList select data)
            .Union
            (from data in new List<ChildData> { parentData.AnotherChildData } select data);

Is there a better way to do this? Thank you.

Morgan M.
  • 846
  • 2
  • 9
  • 27
  • possible duplicate of [Is there a neater linq way to 'Union' a single item?](http://stackoverflow.com/questions/3532176/is-there-a-neater-linq-way-to-union-a-single-item) – Binary Worrier Aug 07 '13 at 07:54
  • That's indeed a duplicate. I didn't see this question before posting mine. Thanks! – Morgan M. Aug 07 '13 at 08:03
  • They can be hard to find if you don't use the same wording, but hey, that's what the community is for :) Anyway now the two questions are linked, so anyone searching that comes across yours will also find the linked question – Binary Worrier Aug 07 '13 at 08:12

2 Answers2

4

You could reduce the code to this:

var query = parentData.ChildDataList
                      .Concat(new [] { parentData.AnotherChildData });
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
  • 3
    @Matten: They have different meanings. Concat simply appends the second list to the first one. Union makes sure that the result contains only distinct items, i.e. it compares the items. This is much more costly and the result will potentially be different and I have the feeling that this is not what the OP wants. When he used `Union` he probably thought about SQL's `UNION ALL` which is `Concat` in LINQ. – Daniel Hilgarth Aug 07 '13 at 07:59
  • 1
    @DanielHilgarth: Dude I feel like a complete idiot. We've had linq for what, 5 years now? and I never knew `Union` returned distinct items. +1 for that alone, thanks mate. – Binary Worrier Aug 07 '13 at 08:15
0

Here is the solution I used (according to Is there a neater linq way to 'Union' a single item?):

public static class LinqHelper
{
    // returns an union of an enumerable and a single item
    public static IEnumerable<T> SingleUnion<T>(this IEnumerable<T> source, T item)
    {
        return source.Union(Enumerable.Repeat(item, 1));
    }

    // returns an union of two single items
    public static IEnumerable<T> SingleUnion<T>(this T source, T item)
    {
        return Enumerable.Repeat(source, 1).SingleUnion(item);
    }
}

Then I can do:

var query = parentData.ChildDataList
            .SingleUnion(parentData.AnotherChildData)
Community
  • 1
  • 1
Morgan M.
  • 846
  • 2
  • 9
  • 27