从列表中选择一个元素

时间:2020-03-03 13:03:35

标签: c# linq

我有以下对象(我在本文中使用JSON来显示我的数据)。

我需要使用LINQ C#选择VehicleClassID = 1的年份。

** [ { “ VehicleClassID”:1 “ VehicleClassName”:“经济”, “ dbo.Vehicles”:[ { “ MakeID”:2 “ ModelID”:8 “年份”:2019 }, { “ MakeID”:6 “ ModelID”:68, “年份”:2019 }, { “ MakeID”:53 “ ModelID”:773, “年份”:2020 } ] }, { “ VehicleClassID”:2 “ VehicleClassName”:“豪华”, “ dbo.Vehicles”:[ { “ MakeID”:2 “ ModelID”:8 “年份”:2020 }, { “ MakeID”:86, “ ModelID”:1157, “年份”:2020 } ] } ] **

2 个答案:

答案 0 :(得分:5)

您可以使用以下查询获取车辆的所有年份

var years = data.Where(x => x.VehicleClassID == 1) //filter
                .SelectMany(x => x.Vehicles)       //select all vehicles
                .Select(x => x.Year)               //select year from each vehicle
                .ToList()                          //return list of years

答案 1 :(得分:0)

使用Quicktype,您可以创建用于解析JSON的类:

namespace QuickType
{
    using System;
    using System.Collections.Generic;

    using System.Globalization;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;

    public partial class Vehicles
    {
        [JsonProperty("VehicleClassID")]
        public long VehicleClassId { get; set; }

        [JsonProperty("VehicleClassName")]
        public string VehicleClassName { get; set; }

        [JsonProperty("dbo.Vehicles")]
        public DboVehicle[] DboVehicles { get; set; }
    }

    public partial class DboVehicle
    {
        [JsonProperty("MakeID")]
        public long MakeId { get; set; }

        [JsonProperty("ModelID")]
        public long ModelId { get; set; }

        [JsonProperty("Year")]
        public long Year { get; set; }
    }

    public partial class Vehicles
    {
        public static Vehicles[] FromJson(string json) => JsonConvert.DeserializeObject<Vehicles[]>(json, QuickType.Converter.Settings);
    }

    public static class Serialize
    {
        public static string ToJson(this Vehicles[] self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
    }

    internal static class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
            Converters =
            {
                new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
            },
        };
    }
}

那么您可以轻松地做到:

var vehicles = Vehicles.FromJson(jsonString);
var v = vehicles.FirstOrDefault(ve => ve.VehicleClassId == 1);
if (v != null) {
    // Your array has multiple years, so I get the first
    var year = v.DboVehicles.FirstOrDefault()?.Year ?? 0;
}