Let's say I have an USAddressModel
class Address {
public string addressline1 {get; set;}
public string addressline2 {get; set;}
public string city {get; set;}
public string state {get; set;}
public string zip {get; set;}
}
If I have an object in my C# code like
var customer = response.Result; // List<Address>
How can I query this list using Linq to create two lists
the first list should contain the minimum required to ship an item to the customer (addressline1, city state and zip).
the second list should be those who have not filled out the complete mailing address. (like only provided a zip or addressline2, city state, zip)
I know that a person could have typed addressline1 into the addressline2 field but for the purpose of this, I was just trying to learn how to use query in C# with linq.
Would this problem be better solved using Lambda?
Thank you for helping.
CodePudding user response:
Try this:
var listOne = response.Result.Where(x => !string.IsNullOrEmpty(x.addressline1) &&
!string.IsNullOrEmpty(x.city) &&
!string.IsNullOrEmpty(x.state) &&
!string.IsNullOrEmpty(x.zip)).ToList();
var listTwo = response.Result.Where(x => string.IsNullOrEmpty(x.addressline1) ||
string.IsNullOrEmpty(x.city) ||
string.IsNullOrEmpty(x.state) ||
string.IsNullOrEmpty(x.zip)).ToList();
CodePudding user response:
As one list is the supplementary of the other you can do it this way too:
var customer = response.Result;
var listOne = customer.Where(x => !string.IsNullOrEmpty(x.addressline1) &&
!string.IsNullOrEmpty(x.city) &&
!string.IsNullOrEmpty(x.state) &&
!string.IsNullOrEmpty(x.zip)).ToList();
var listTow = customer.Where(x => !listOne(y => y.Equals(x))).ToList();