saraswathi
saraswathi

Reputation: 69

Retrieving Values from List<Objects> of different dataTypes

I'm storing different customobject in a List of Objects(List<(Objects)>). Below is my structure of the List.My customobjects doesn't inherit from the same class

[
      {
    "id": "1",
    "uniqueid": "secret",
    "emailaddress": "[email protected]", 
    "stateCode": "Xyz",
    },
    {
    "id": "2",
    "Name": "secret",
    "Age": "[email protected]",     
    },
]

I want to check whether an object is present in the list based on the id field.I want to try reflection but couldn't find any helpful article that is performing reflection on System.Object

Upvotes: 0

Views: 172

Answers (3)

John Wu
John Wu

Reputation: 52290

It's not ideal, but if you have to store unrelated types in the same list, you can cast to dynamic:

var results = list.Cast<dynamic>().Where( o => o.Id == 1 );

Example on DotNetFiddle

Upvotes: 2

mxmissile
mxmissile

Reputation: 11681

Use this extension method ripped from this question:

public static object GetPropValue(this object src, string propName)
{
     return src.GetType().GetProperty(propName).GetValue(src, null);
}

usage:

foreach(var o in Objects)
{
    if(o.GetPropValue("id") == someId)
    {
        // do something
    }
}

You might have to do some converting/unboxing to get equatable values depending on the property's underlying data type. As others have pointed out, this is "magic" and "fuzzy". You are better off using an abstract class or an interface for your objects. Also this comes with all the fun Reflection caveats.

Upvotes: 0

Manoj Choudhari
Manoj Choudhari

Reputation: 5634

First of all, I agree with the comments.

This is not the best design / best usage of JSON structure.

In a JSON array, you should have only objects of similar type. That way, you will never come into this situation.

Solution to your problem:

Option 1:

In that json array, you can get list of JObjects using newtonsoft API.

From the JObject you can read ID property using below syntax, assuming categories is the JArray you want to search into:

var list = categories.Select(c => (string)c["id"] == 1).ToList();

Option 2:

You can deserialize whole collection in a simple object which has only ID property.

e.g.

public interface IDummyInterface
{
    public string Id {get; set;}
}

public class SomeDummyClass : IDummyInterface

Using this dummy class you can call Deserialize method to get all the objects and then process them. But remember you will not be able to use other properties in option 2 approach.

Upvotes: 1

Related Questions