Well, the Select(el => el)
isn't doing you any good to start with.
I suggest you use SingleOrDefault
:
var productId = element.Elements("ProductId").SingleOrDefault();
if (productId != null)
filter.ProductId = Convert.ToInt32(productId.Value);
Note that that handles the case where there are no ProductId elements, but will throw an exception if there's more than one. If that's actually a valid case, then your current code (without the redundant Select
call) is reasonable.
EDIT: You could get away from this with:
var productId = element.Elements("ProductId")
.Select(elt => elt.Value)
.SingleOrDefault();
filter.ProductId = Convert.ToInt32(productId ?? filter.ProductId.ToString());
But that's pretty ghastly ;)
Basically you've got a condition - you only want to set the ProductId
if it's specified. An "if" statement is the generally accepted way of conditionally executing code :)
There are alternatives:
filter.ProductId = productId == null
? filter.ProductId
: int.Parse(productId);
If you don't mind filter.ProductId
being set to 0 if there's no ID specified, then you can just use:
filter.ProductId = Convert.ToInt32(element.Elements("ProductId")
.Select(elt => elt.Value)
.SingleOrDefault());
(due to the way that Convert.ToInt32
returns 0 when passed a null argument.)