简体   繁体   中英

How to check variable type in one line, inside creation block in C#

I'm creating a custom Json to Object conversion, as I need to handle one of the JTokens differently depending on if it's a string or an integer. However I'm not sure how to obtain the parsing in a compact and clean way.

Code:

    public class MyClass
    {
        public int Id { get; set; }
        public string SomeOtherDataPoint { get; set; }
    }

    public int CreateNewIntIdBasedOnString(string stringId)
    {
        //some code
    }

    public IEnumerable<MyClass> ConvertJArrayToMyObjects(JArray array)
    {
        return array.Select(d => new MyClass() {
            Id = ((JObject)d).GetValue("id") == int ? ((JObject)d).GetValue("id") : CreateNewIntIdBasedOnString((string)((JObject)d).GetValue("id")),
            SomeOtherDataPoint = (string)((JObject)d).GetValue("someOtherDataPoint")
        });
    }

((JObject)d).GetValue("id") == int isn't a thing, so I need something like int.TryParse which work on one line. I could create a method for it, but it seems weird that this isn't common enough that there isn't a standardized way of doing it.

I think trying to keep everything in one expression is the wrong approach -- you end up repeating yourself unnecessarily.

If I'm interpreting what you want correctly, I'd write it as something like:

public static IEnumerable<MyClass> ConvertJArrayToMyObjects(JArray array)
{
    return array.Values<JObject>().Select(d =>
    {
        var id = d.Value<string>("id");
        return new MyClass()
        {
            Id = int.TryParse(id, out var intId) ? intId : CreateNewIntIdBasedOnString(id),
            SomeOtherDataPoint = d.Value<string>("someOtherDataPoint"),
        };
    });
}

If you really want to stuff it in a single expression, you can (ab)use a var pattern:

public static IEnumerable<MyClass> ConvertJArrayToMyObjects(JArray array)
{
    return array.Values<JObject>().Select(d =>
        new MyClass()
        {
            Id = d.Value<string>("id") is var id && int.TryParse(id, out var intId) ? intId : CreateNewIntIdBasedOnString(id),
            SomeOtherDataPoint = d.Value<string>("someOtherDataPoint"),
        });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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