2

I am looking at trying to use a Linq query to determine if the following JSON is true if it contains a product that has a SKU of 12345 OR a TypeCode of "C".

"[{\"SKU\":\"12345\",\"Description\":\"Test Part 12345\",\"TypeCode\":\"A\",\"Cost\":24.99},{\"SKU\":\"54567\",\"Description\":\"Test Part 54567\",\"TypeCode\":\"B\",\"Cost\":9.99},{\"SKU\":\"QWZ2342\",\"Description\":\"Test Part QWZ2342\",\"TypeCode\":\"C\",\"Cost\":19.99}]"

I have been working with the Json.net (http://james.newtonking.com/projects/json-net.aspx)

1 Answer 1

2

At first, you have to deserialize the JSON into a C# object, lets say Product.

class Product
{
    public int SKU { get; set; }
    public string Desc { get; set; }
    public string TypeCode { get; set; }
    public decimal Cost { get; set; }
}

then, using .NET's JavaScriptSerializer (System.Web.Script.Serialization), convert the json string to become List of your custom objects.

string json = "[{\"SKU\":\"12345\",\"Description\":\"Test Part 12345\",\"TypeCode\":\"A\",\"Cost\":24.99},{\"SKU\":\"54567\",\"Description\":\"Test Part 54567\",\"TypeCode\":\"B\",\"Cost\":9.99},{\"SKU\":\"QWZ2342\",\"Description\":\"Test Part QWZ2342\",\"TypeCode\":\"C\",\"Cost\":19.99}]"

JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
List<Product> productList = new List<Product>();
productList = jsonSerializer.Deserialize<List<Product>>(json);

the last step, using simple linq query, you cant check whether your product exist on the list:

var Found = from o in productList
                    where o.SKU == 12345
                    select o.SKU;
if (Found.Count() > 0)
    return true;
else
    return false;
Sign up to request clarification or add additional context in comments.

3 Comments

When I run the linq query I am getting back all results and not what is filtered by the where statement. My List<Products> contains 80 items. When I add a where clause and specify a value that does not exist (such as o.SKU == "ZZZZZ") I still get a var Found that is not null and the count is 80 items.
I noticed the Sourc count = 80 but the Results View is empty if the query where condition is not true. However, checking if Found != null is is returning true even if the Result View is empty. How might be the best way to determine if the query returned any results?
Ok I think I have it. I am using the Count() method such as int count = Found.Count();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.