How check data existing or not in c# and data valid json or not

Binumon George 161 Reputation points
2023-01-12T16:19:13.3933333+00:00

Hi All,

      I am creating on web API for client using complex Model. Structure of model i am giving below

Public Class Organization

{

public Int Id{get; set;}

public string Name {get; set;}

public string ?website { get; set; }

public IEnumerable<Location> get; set; }

public IEnumerable<Contact> get; set; }

}

public class Location

{

public Int Id{get; set;}

public string Name {get; set;}

}

public class Contact

{

public Int Id{get; set;}

public string Name {get; set;}

}

As you can see Organization is my main class inside that i am using location and contact classes as list. In foreach loop i am checking condition like below

if (OrgData.contact.Count() > 0)

{

}

But user not passing any location or contact information how i manage while retrieving data. The above condition will fail. These location and contact is not mandatory. And also possibility in valid json data. How can i check data is valid or not?


ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,742 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,210 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 69,501 Reputation points
    2023-01-12T17:00:40.92+00:00

    you need to decide if contact defaults to empty collection, or can be null. if you want a default, then create an instance of the collection in Organization constructor. if not test for null:

    if (OrgData.contact != null && OrgData.contact.Count() > 0)

    or

    if (OrgData.contact?.Count() > 0)

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.