简体   繁体   English

在C#中过滤对象值

[英]Filtering Object values in C#

i've got a C# web Api receiving the following object : 我有一个C#Web Api接收以下对象:

     "cars": {
       "bmw": true,
       "benz": false,
       "kia": true,
       "hyundai": false,
       "madza": false,
       "ford": false
   }

the class property is as follows : class属性如下:

 public CarsViewModel cars{ get; set; }

How can i get all the values that are true in the above object? 我如何获得上述对象中所有正确的值?

You can parse the received object into the dictionary and select the key only if value is true. 您可以将接收到的对象解析到字典中,并仅在value为true时选择键。

string json = "{\"bmw\": true,\"benz\": false,\"kia\": true,\"hyundai\": false,\"madza\": false,\"ford\": false}";
var dict = JsonConvert.DeserializeObject<Dictionary<string,bool>>(json);

List<string> cars = dict.Where(x=>x.Value).Select(y=>y.Key).ToList();

You can check the result by: 您可以通过以下方式检查结果:

cars.ForEach(y => Console.Write("{0}\n", y));

PS. PS。 For serializing you have to use Newtonsoft.Json namespace. 为了进行序列化,您必须使用Newtonsoft.Json命名空间。

you try this code 您尝试此代码

 string jsonstring = "{\"cars\": {\"bmw\": \"true\", \"benz\": \"false\",  \"kia\": \"true\",  \"hyundai\": \"false\", \"madza\": \"false\",  \"ford\": \"false\"}}";
 dynamic data = JObject.Parse(jsonstring); 
 CarsViewModel obj = new CarsViewModel(); 
 var mydetails2 = JsonConvert.SerializeObject(data.cars);
 var mydetails3 = JsonConvert.DeserializeObject<Dictionary<string, bool>>(mydetails2);

  foreach (var pair in mydetails3)
    {
       // Console.WriteLine("{0}, {1}", pair.Key, pair.Value);
        if (pair.Value == true)
        {
            if (pair.Key == "bmw")
            {
                obj.bmw = pair.Value;
            }
            else if (pair.Key == "benz")
            {
                obj.benz = pair.Value;
            }
            else if (pair.Key == "kia")
            {
                obj.kia = pair.Value;
            }
            else if (pair.Key == "hyundai")
            {
                obj.hyundai = pair.Value;
            }
            else if (pair.Key == "madza")
            {
                obj.madza = pair.Value;
            }
            else if (pair.Key == "ford")
            {
                obj.ford = pair.Value;
            }

        }
    }

I hope its helpful to you.. 希望对您有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM