M
M
Maxim Usachov2016-09-22 10:53:21
.NET
Maxim Usachov, 2016-09-22 10:53:21

How to combine lists of objects that have dictionaries in their composition?

Hello. I am making a parser for a specific set of medical sites.
A search request is sent to each site with part of the name of the drug, for example "paratz".
From each site I receive in the search results a list of objects with prices - List and different articles.
In the PricedDrug class, I defined a dictionary (string-site, price). All medicines are comparable by article.
At the output of the program, I want to get the same List, but with the price and site dictionaries filled in.
Which of the LINQ arsenal is better to use in this case?
We have a class

public class PricedDrug: IComparable<PricedDrug>
    {
        public PricedDrug()
        {
            _prices = new Dictionary<PriceSource, float>();
        }
        protected string _article;
        private Dictionary<PriceSource, float> _prices;
        public int CompareTo(PricedDrug other)
        {
            return _article.CompareTo(other.article);
        }
        //далее геттеры, сеттеры
    }

Next do
foreach(site in sitelist)
{
    List<PricedDrug>  search_results =  site.Seach(text);
}

And we get the following collection:
{
{ _prices: { "site1", 100}, _article: "1"}
{ _prices: { "site2", 110}, _article: "1"}
{ _prices: { "site3", 10} , _article:"2"}
{ _prices: { "site2", 12}, _article:"2"}
}
How to get the final collection of the form in one request:
{ _prices: [ { "site1", 100},{ "site2", 110} ], _article:"1"}
{ _prices: [ { "site2", 10}, { "site3", 12} ]_article:"2"}
So collapse by article?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Kamalov, 2016-09-23
@maxus01

For example, like this:

var finalResults =
      from srGroup in searchResults.GroupBy(sr => sr.article)
      let prices = srGroup.SelectMany(sr => sr.prices).ToDictionary(p => p.Key, p => p.Value)
      let article = srGroup.First().article
      select new PricedDrug { article = article, prices = prices };

M
MrDywar Pichugin, 2016-09-23
@Dywar

GroupBy

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question