0

I have a store procedure that returns an N amount of rows.

For the sake of simplicity in my backend is this POCO that will map:

public class Car
{
  public int Id { get; set; }
  public string Brand { get; set; }
  public int OwnerId{ get; set;}
}

At the same time I also have the following POCO:

public class Owner
{
  public int Id { get; set; }
  public string FirstName { get; set; }
}

Now what I want to achieve is the following, having the list:

List<Car> lstCar = db.sp.AllMyCars()
    .Select(car => new Car()
     {
        Id = car.Id,
        Brand = car.Brand,
        OwnerId = car.OwnerId
     }).ToList();

Now I want to save in a dictionary of type Dictionary<int,List<Owner>>

EDIT:

To clarify, you already have a list of Cars List<Car> as lstCar, now you want to group them by Id and a list of Owners, which we will need to create a list of owners and for each element of list of car we will need to add and fill this lists as Cars (you will only fill the id, its ok, it doesnt matter).

Example:

enter image description here

your int in your dictionary will be "Number" and the only field that you will fill in your List is the OwnerId.

So you will want to group by the Number a list of Owner Objects, in this case for example number 44 would return 5 Owner Objects with their Id as 2,3,4,5 and 6.

Nickso
  • 785
  • 1
  • 10
  • 32
  • `Dictionary,int>` - can you please clarify what you want to achieve with that and show an example of the dictionary? – Alexei Levenkov Feb 21 '19 at 19:10
  • "in this case for example number 44 would return 5 Owner Objects with their Id as 2,3,4,5 and 6" - that describes `Dictionary>` - can you please re-read your question and make sure it is consistent? – Alexei Levenkov Feb 21 '19 at 19:48
  • That is what I want Alexei Im sorry I will edit it. – Nickso Feb 21 '19 at 19:57

1 Answers1

0

from the definition of Dictionary<TKey, TValue> where TKey is for key and TValue is for value object. Thus Dictionary<List<Owner>, int> grouped ıs needed to be Dictionary<int, List<Owner>> grouped.

on the other hand, I believe that you are looking for Dictionary<int, Owner> grouped

 Dictionary<int, Owner> grouped = 
    myList.Items
        .GroupBy(elem => elem.Id)
        .ToDictionary(com => com.Key, com => new Owner() 
          { 
            Id = elem.Id, 
            Firstname = elem.Firstname 
          });
Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72