0

How could I find a specific id in this list?

var contactList = JsonConvert.DeserializeObject<ContactList>(jsonString);

contactList.contacts.FindAll(x => x.id == item.id);

The code above is not filtering by id and is returning all rows from object.

(Visual Studio is not showing me .Where clause only .Find and .FindAll)

C# code

namespace RestDemo.Model 
{ 
   public class Phone 
   { 
      public string mobile { get; set; } 
      public string home { get; set; } 
      public string office { get; set; } 
   } 

   public class Contact 
   { 
      public int id { get; set; } 
      public string name { get; set; } 
      public string email { get; set; } 
      public string address { get; set; } 
      public string gender { get; set; } 
      public Phone phone { get; set; } 
   } 

   public class ContactList 
   { 
      public List<Contact> contacts { get; set; } 
   } 
}

Json:

{ "contacts": [     {           "id": 200,          "name": "Ravi Tamada",          "email": "ravi@gmail.com",          "address": "xx-xx-xxxx,x - street, x - country",            "gender": "male",           "phone": {              "mobile": "+91 0000000000",             "home": "00 000000",                "office": "00 000000"           }       },      {           "id": 201,          "name": "Klev Krist",           "email": "klev@gmail.com",          "address": "xx-xx-xxxx,x - street, x - country",            "gender": "male",           "phone": {              "mobile": "+91 0000000000",             "home": "00 000000",                "office": "00 000000"           }       },      {           "id": 202,          "name": "Paul Neil",            "email": "paul.neil@gmail.com",         "address": "xx-xx-xxxx,x - street, x - country",            "gender": "male",           "phone": {              "mobile": "+91 0000000000",             "home": "00 000000",                "office": "00 000000"           }       }   ]}

Thanks

Marcio
  • 162
  • 1
  • 12

4 Answers4

0

Assuming you want to find a certain id, we'll call it

var idToFind = "myID";

To find all contacts with said ID:

var contacts = contactList.contacts.Where(contact=> contact.id == idToFind);

To find at least one contact with said ID:

var contactWithID = contactList.contacts.FirstOrDefault(contact=> contact.id == idToFind);
// Before using, check if null, means no contact matched the id.
if(contactWithID != null)
{
   // A contact was found.
}
else
{
   // No contact matching that id is found.
}
ChoopTwisk
  • 1,296
  • 7
  • 13
0

As per your comment on @Tenretni's answer, I guess you missed to use System.Linq library in your code.

Import System.Collections.Generic and System.Linq in your code and use FirstOrDefault() or .Where() clause

using System.Collections.Generic;
using System.Linq;

//…

string jsonString = @"{ 'contacts': [{ 'id': 'c200', 'name': 'Ravi Tamada', 'email': 'ravi@gmail.com', 'address': 'xx-xx-xxxx,x - street, x - country', 'gender': 'male', 'phone': { 'mobile': '+91 0000000000', 'home': '00 000000', 'office': '00 000000' } }] }";

var contactList = JsonConvert.DeserializeObject<ContactList>(jsonString);
var item = "c200";
var result = contactList.contacts.FirstOrDefault(x => x.id == item);
Console.WriteLine(result.name);

//If you have multiple records with same ID then you can try where clause
var result = contactList.contacts.Where(x => x.id == item);      //Here result will be list of Contact

.Net Fiddle

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
0

The FindAll method does not assign an object to the search result.

You have to keep the search result somewhere.

Example Multi Result

If you are expecting multiple results

var contactList = JsonConvert.DeserializeObject<ContactList>(jsonString);
var findedContact = contactList.contacts.FindAll(x => x.id == item.id);
//You business codes..

Example Single Result

If you are only waiting for 1 result

var contactList = JsonConvert.DeserializeObject<ContactList>(jsonString);
var oneContact = contactList.contacts.Find(x => x.id == item.id);
if(oneContact ==null){
    //not found business codes
}
else {
   //find result business codes
}
Fatih GÜRDAL
  • 1,489
  • 1
  • 17
  • 19
  • .Find() did not work for 1 result. It brings a couple of rows yet. I will use Linq instead. Thanks. – Marcio Sep 18 '19 at 14:05
  • @user2250504 It is not mandatory to use linq. For this situation Find(single) or FindAll(multi). I said two answers in the answer. – Fatih GÜRDAL Sep 18 '19 at 14:44
  • Ok, In mocked tests Find() or Where() are working successfully. I will try to implement in oficial code later. Thanks. – Marcio Sep 18 '19 at 14:57
0

Specific to your case, I am using the same Model structure to deserialize your JSON and then use the Where linq clause to achieve what you require. A working fiddle can be found at: https://dotnetfiddle.net/SAcFja

Code:

using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var jsonString = @"{ 'contacts': [{ 'id': 200, 'name': 'Ravi Tamada', 'email': 'ravi@gmail.com', 'address': 'xx-xx-xxxx,x - street, x - country', 'gender': 'male', 'phone': { 'mobile': '+91 0000000000', 'home': '00 000000', 'office': '00 000000' } }] }";
        var data= JsonConvert.DeserializeObject<ContactList>(jsonString);
        //Console.WriteLine(data.contacts);

        var found=data.contacts.Where(x=>x.id.ToString()=="200");

        foreach(var value in found)
        {
          Console.WriteLine(value.id);
          Console.WriteLine(value.address);     
        }       
    }
}

   public class Phone 
   { 
      public string mobile { get; set; } 
      public string home { get; set; } 
      public string office { get; set; } 
   } 

   public class Contact 
   { 
      public string id { get; set; } 
      public string name { get; set; } 
      public string email { get; set; } 
      public string address { get; set; } 
      public string gender { get; set; } 
      public Phone phone { get; set; } 
   } 

   public class ContactList 
   { 
      public List<Contact> contacts { get; set; } 
   }

Output when id=200:

200
xx-xx-xxxx,x - street, x - country
Rahul Sharma
  • 7,768
  • 2
  • 28
  • 54
  • Visual Studio is not showing me .Where() clause to filter object content... only .Find() or .FindAll() – Marcio Sep 18 '19 at 12:42
  • @user2250504 You would have to import `System.Linq` in your project. – Rahul Sharma Sep 18 '19 at 12:42
  • Ok I will try. Thanks. – Marcio Sep 18 '19 at 12:43
  • @user2250504 What is your Framework version? You can check that by Going to Project -> Properties -> Application and check the Target Framework property. If your target framework is prior to 3.5 then `System.Linq` wont work since it was introduced on .NET Framework 3.5. More on this topic can be found here: https://stackoverflow.com/questions/24659934/visual-studio-does-not-recognize-system-linq – Rahul Sharma Sep 18 '19 at 12:48
  • Version 4.7 Thanks – Marcio Sep 18 '19 at 14:02
  • Okay, you might missing a reference then. You would need to add it explicity. I hope the link that I gave in my previous comment helped you to resolve this. – Rahul Sharma Sep 18 '19 at 14:05