Advertisement
NelIfandieva

C#DBAdvanced_JsonProcessing_ProductShop_Ex08

Mar 28th, 2019
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.81 KB | None | 0 0
  1. public static string GetUsersWithProducts(ProductShopContext context)
  2.         {
  3.             var count = context.Users
  4.                 .Where(u => u.ProductsSold.Any(p => p.BuyerId != null))
  5.                 .Select(u => new
  6.                 {
  7.                     firstName = u.FirstName,
  8.                     lastName = u.LastName,
  9.                     age = u.Age,
  10.                     productsSold = u.ProductsSold
  11.                     .Select(p => new
  12.                     {
  13.                         name = p.Name,
  14.                         price = p.Price
  15.                     })
  16.                 })
  17.                 .Count();
  18.  
  19.             string countToString = JsonConvert.SerializeObject(count);
  20.  
  21.             var collection = context.Users
  22.                 .Where(u => u.ProductsSold.Any(p => p.BuyerId != null))
  23.                 .Select(u => new
  24.                 {
  25.                     firstName = u.FirstName,
  26.                     lastName = u.LastName,
  27.                     age = u.Age,
  28.                     soldProducts = u.ProductsSold.Count,
  29.                     products = u.ProductsSold
  30.                     .Select(p => new
  31.                     {
  32.                         name = p.Name,
  33.                         price = p.Price
  34.                     })
  35.                 })
  36.                 .ToList();
  37.  
  38.             var jsonCollection = JsonConvert.SerializeObject(collection, Formatting.Indented, new JsonSerializerSettings
  39.             {
  40.                 NullValueHandling = NullValueHandling.Ignore
  41.             });
  42.             /*JsonConvert.SerializeObject(response, Newtonsoft.Json.Formatting.None, new JsonSerializerSettings {
  43.             NullValueHandling = NullValueHandling.Ignore
  44.                             });*/
  45.             return $"{"{"}\n\"usersCount\":{countToString},\n\"users\":\n{jsonCollection}";
  46.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement