I have 2 IEnumerables which are of type 'Product' - totalProducts and ProductsChosen. As the names suggest totalProducts holds all the products available and ProductsChosen holds the products chosen by the user .
The Product class has properties Id
,number
, and IEnumerable<AdditonalOptions> options
.
I am trying to merge these 2 IEnumerables like this
public IEnumerable<Product> MergeProducts(IEnumerable<Product> Products, IEnumerable<Product> ProductsChosen)
{
return ProductsChosen.Concat(Products.Where(r => !ProductsChosen.Any(x => x.ProductId.Equals(r.ProductId))));
}
I have used the code to merge from here
This code wor开发者_StackOverflowks fine only if I consider the product ids but I would also like to merge the IEnumerable<AdditionalOption> options
of the productsChosen
with that of the totalProducts
if the Product Ids are same.But I am not sure how to do that.
Could someone please help me with that?
Thanks
As the chosen products have different options that the total products they must be distinct instances. Since you have said that total products are all that are available then I assume that the set of chosen product ids must be a subset of the product ids.
Also, since the chosen products are distinct instances then it is possible that there may be zero or more chosen products per each total product so my solution works for this case too. It will equally work if there are only zero or one.
Further, since they are distinct instances and the options
property is an IEnumerable
it made sense to me to create a new set of instances for the merged products so as to not alter the original set of total products.
public IEnumerable<Product> MergeProducts(
IEnumerable<Product> Products,
IEnumerable<Product> ProductsChosen)
{
return
from p in Products
join pc in ProductsChosen on p.Id equals pc.Id into pcs
select new Product()
{
Id = p.Id,
number = p.number,
options = p.options
.Concat(
from pc2 in pcs
from ao in pc2.options
select ao).ToArray(),
};
}
You didn't explain what number
property is, so I've just done a simple assignment for this value from the Products
list and ignored this value from the ProductsChosen
list.
Also, you didn't say how the AdditionalOptions
needed to be merged. This is no Merge
method for enumerables. You need to use something like Concat
or Union
to do a merge. I've chosen Concat
but that easy to change.
Does this work for you?
精彩评论