Lambda expression C# Union Where

15,100

Solution 1

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.

Solution 2

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

You need to add the second IEnumberable 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

Solution 3

This will avoid cases where there is an Error but Name and Age have values or if there is no Error but Name and Age don't have values.

Separate:

var p1Err = p1.Where(p => String.IsNullOrEmpty(p.Error) && !String.IsNullOrEmpty(p.Name) 
                   && !String.IsNullOrEmpty(p.Age));
var p1NoErr = p1.Where(p => !String.IsNullOrEmpty(p.Error) && String.IsNullOrEmpty(p.Name) 
                    && String.IsNullOrEmpty(p.Age));

var p2 = p1Err.Union(p1NoErr)
              .ToArray();

Combined:

var p2 = p1.Where(p => String.IsNullOrEmpty(p.Error) && !String.IsNullOrEmpty(p.Name) 
                   && !String.IsNullOrEmpty(p.Age))
           .Union(p1.Where(ip => !String.IsNullOrEmpty(ip.Error) 
                   && String.IsNullOrEmpty(ip.Name) && String.IsNullOrEmpty(ip.Age)))
           .ToArray();
Share:
15,100
ihorko
Author by

ihorko

Updated on June 04, 2022

Comments

  • ihorko
    ihorko almost 2 years

    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?