Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 980
ihorko Avatar asked Aug 14 '26 17:08

ihorko


1 Answers

p1.Where(c => string.IsNullOrEmpty(c.Error))
  .Union(p1.Where(d => !string.IsNullOrEmpty(d.Error)))
  .ToArray()

You need to add the second IEnumerable inside the .Union. And no need to project again since the objects are already the type you need.

Although it's kind of moot in this case, the result is the same as p1

like image 200
AD.Net Avatar answered Aug 16 '26 06:08

AD.Net



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!