0

I have this class:

    public class Campaign{
     public   int campaign_id { get; set; }
     public   string campaign_name { get; set; }
     public   int representative_id { get; set; }}

And I can deserialize the JSON to a List like this:

 Campaigns = JsonConvert.DeserializeObject<List<Campaign>>(jsonstring);

But I want to access the items base on the campaign_name, how can I do that? How to Deserialize it to a dictionary where the value will be the object and the key will be the campaign_name? Thank you.

Rahul Sharma
  • 7,768
  • 2
  • 28
  • 54
ILovePizza
  • 141
  • 1
  • 8
  • Take a look at the `.ToDictionary` extension method on `List` (though note you'll get an error if two entries have the same `campaign_id`. – ProgrammingLlama Jan 28 '22 at 08:54

2 Answers2

1

You can use the ToDictionary method to convert your List. You can read more at MSDN:

var dict = Campaigns.ToDictionary(x => x.campaign_id);

Note that this will fail if an item exists in the list multiple times so you can Distinct:

var dict = Campaigns.Distinct().ToDictionary(x => x.campaign_id)
Rahul Sharma
  • 7,768
  • 2
  • 28
  • 54
0

For the Dictionary you can go with:

var dictionaryOfCampaign = Campaigns.ToDictionary(x => x.campaign_id, y => y);

If you don't want to use a dictionary you can filter your List using a linq query like this:

var filteredCampaign = Campaigns.Where(x => x.campaign_name.Equals("TEST"));
var filteredCampaign2 = Campaigns.Where(x => x.campaign_name.Contains("TEST"));

Remember to add in your using System.Linq

theLaw
  • 1,261
  • 2
  • 11
  • 23