开发者

Consolidate/Merge data from TWO IEnumerable Lists into ONE

I have following domain objects in my application:

 [Serializable]
    public class Supplier
    {
        public virtual string SupplierType { get; set; }
        public virtual string SupplierCode { get; set; }

        public virtual string Name { get; set; }
        public virtual string Description { get; set; }
        public virtual string Rating { get; set; }
        public virtual 开发者_Python百科string WebsiteURL { get; set; }

        public virtual IList<Address> Address { get; set; }

    }

    [Serializable]
    public class CargoSupplier : Supplier
    {
        public virtual IList<Image> Images { get; set; }
        public virtual string OpeningTime { get; set; }
        public virtual string ClosingTime { get; set; }

        public virtual IList<Product> Products { get; set; }
    }

I have to goto two seperate repositories for getting descriptive content (from database) and pricing (from external webservice) and will have two seperate enumerations populated with data (descriptive content & pricing):

IEnumerable<CargoSupplier> cargoSuppliers_Pricing
IEnumerable<CargoSupplier> cargoSuppliers_Content

cargoSuppliers_Content will have all fields populated with data EXCEPT IList<Product> and cargoSuppliers_Pricing will have SupplierType, SupplierCode and IList<Product> fields populated with data. Combination of "SupplierType" amd "SupplierCode" would be the key.

Now I have to merge the content and pricing into one enumeration so I can return IEnumerable<CargoSupplier> cargoSuppliers to my Controllers & Views. What is the best way to merge/consolidate these two lists into one?


Are you looking for Union or am i missing something in the question?

var mergedList = list1.Union(list2).ToList();

remember to import the System.Linq namespace


It sounds like you don't want one list that just contains all the items in either list - it sounds like you need to merge individual items. Something like this:

var query = from pricing in cargoSuppliers_Pricing
            join content in cargoSuppliers_Content
            on pricing.SupplierCode equals content.SupplierCode
            select new CargoSupplier
            {
                // Copy properties from both objects here
            };

Within the "select" part you would take the pricing parts from "pricing" and the content parts from "content", building a CargoSupplier object which has both bits.

Is that what you were after?


Use Enumerable.Concat:

Concatenates two sequences.

Example:

var result = cargoSuppliers_Content.Concat(cargoSuppliers_Pricing);


Seen the Union() extension method? That should do what your after

IEnumerable<CargoSupplier> allCargoSuppliers = cargoSuppliers_Pricing.Union(cargoSuppliers_Content);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜