Search code examples
c#asp.netlinqlambda

Lambda expression C# Union Where


I have objects of class

public class Person
    {
        public string Error { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }

some have Error (and no Name and Age) some have no Error (and Name and Age)

Person[] p1 = new Person[] { new Person { Error = "Error1" }, new Person { Name = "Name1", Age = 1 } };



Person[] p2 = p1
                .Where(c => string.IsNullOrEmpty(c.Error))
                .Select(
                    c => new Person { Name = c.Name, Age = c.Age }
                 ).ToArray()
                 Union()
                .Where(d => !string.IsNullOrEmpty(d.Error))
                .Select(
                    d => new Person { Error = d.Error }
                 ).ToArray()

I need create second array p2, where I can select all persons objects from p1 which have Error, and Union all persons from same p1 which have no Error.

I need something like in code above, but it's not working. How can I write it in one lambda clause?

Thanks a lot?


Solution

  • Ok, found solution myself, it should be like:

    Person[] p2 = p1
                .Where(c => string.IsNullOrEmpty(c.Error))
                .Select(
                    c => new Person { Name = c.Name, Age = c.Age }
                 )
                .Union(
                p1.Where(d => !string.IsNullOrEmpty(d.Error))
                .Select(
                    d => new Person { Error = d.Error }
                 )
                 ).ToArray();
    

    Sorry, maybe my answer was not so clear. Thanks all for replies.