Radost
Radost

Reputation: 131

LINQ: Getting item from dictionary by key and also its values then assign them to variable

In Parts class we have Data dictionary that contains key "Number" and value "1" for example. The key is always called "Number" and the value is always string of some number 1,2,3 etc. I want to assign to one variable (List) all items that has the key "number" with their values and then to group them by the id in Parts. So in the end the result should be the Id from Parts, Number and its value.

   public class People
   {
   public List<Parts> Parts { get; set; }
   }


   public class Parts
   {
   public string Name {get;set;}
   public string Id {get;set;}
   public Dictionary<string,string> Data {get;set}
   }

   var msf = new People();

Currently my example that does not work properly with linq :

 var temp = msf
   .Parts
   .Select(s => s.Data.Keys.Where(key => key.Contains("Number"))
   .ToList()
   .Select(s = > s.Value));

Can someone give me better solution for this scenario code with linq?

  "People":[  
  "id":"1234567"

   "Parts":[

   "id":"234567",
   "name":"Lqlq"
   "Data":{ 
   "number" : "1"
     }

  "id":"3424242",
   "name":"Lqlq2"
   "Data":{ 
   "number" : "2"
     }
 ]
    ]

Upvotes: 0

Views: 187

Answers (2)

Leonardo Herrera
Leonardo Herrera

Reputation: 8406

Here's an alternative syntax.

var temp = from part in msf.Parts
        where part.Data["Number"] == "2"
        select part;

Usually is a good idea to ask your questions using an MCVE - here's some code that can be pasted in Linqpad:

void Main()
{
    var msf = new People() {
        Parts = new List<Parts> {
            new Parts { Name = "Lqlq", Id = "234567", Data = new Dictionary<string, string> { { "Number", "1"} } },
            new Parts { Name = "Lqlq2", Id = "3424242", Data = new Dictionary<string, string> { { "Number", "2"} } },
        }
    };
    var temp = from part in msf.Parts
        where part.Data["Number"] == "2"
        select part
    ;

    temp.Dump();
}

public class People
{
    public List<Parts> Parts { get; set; }
}

public class Parts
{
   public string Name { get; set; }
   public string Id { get; set; }
   public Dictionary<string, string> Data { get; set; }
}

Upvotes: 2

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43936

This should give you a Dictionary<string, List<string>> containing a list of ID strings for each "Number" value:

var idsByNumber = msf.Parts.Where(p => p.Data.ContainsKey("number"))    // filter for all that have a number
             .Select(p => new { ID = p.ID, Number = p.Data["number"] }) // select ID and the number value
             .GroupBy(x => x.Number)                                    // group by number
             .ToDictionary(g => g.Key, g => g.ToList()); // create dictionary number -> id list

Upvotes: 3

Related Questions