I'm iterating through two lists to find matching objects. The objects have two string properties, Id1
and Id2
below. If Id1
is not null
, empty or whitespace, I want to use it to find a matching object in the other list. Otherwise I want to make use of Id2
.
If both Id1
and Id2
are set to null by the extension method on either p
or p2
, I want to skip the iteration, since I know that I won't find a match.
public static string NullIfEmptyOrWhiteSpace(this string value)
{
return string.IsNullOrEmpty(value) ? null : value;
}
foreach (Product p2 in productList1)
{
Product match = productList2.FirstOrDefault(p =>
{
string pId = p.Id1.NullIfEmptyOrWhiteSpace() ??
p.Id2.NullIfEmptyOrWhiteSpace();
string p2Id = p2.Id1.NullIfEmptyOrWhiteSpace() ??
p2.Id2.NullIfEmptyOrWhiteSpace();
if (pId == null || p2Id == null)
return false;
return pId.Equals(p2Id);
});
// do stuff with match
}
This seems to work, but it feels like I'm re-inventing the wheel here. Are there any built in methods that I can make use of to simplify the code? Perhaps a class that implements IEqualityComparer
?
Example use case:
List<Product> list1 = new List<Product>()
{
new Product() { Id1 = "123", Id2 = null },
new Product() { Id1 = "435", Id2 = null },
new Product() { Id1 = null, Id2 = "123" }
}
List<Product> list12 = new List<Product>()
{
new Product() { Id1 = "123", Id2 = null },
new Product() { Id1 = "456", Id2 = null },
new Product() { Id1 = null, Id2 = "123" }
}
// do something with each matching item in the first list
// which would be item #1 and item #3 above
NullIfEmptyOrWhiteSpace
with the built-in methodstring.IsNullOrWhiteSpace
(although you'll have to change the logic around a little). As it is right now it's hard to follow what you're trying to do. \$\endgroup\$products
). \$\endgroup\$