Ronak Shetiya
Ronak Shetiya

Reputation: 980

Looping over the value inside property which is present inside the struct

I have created a struct which have some properties such as

public struct DeviceDetailModel
{
  public static readonly DeviceDetailModel DT851P = new DeviceDetailModel("851P","v1","v2");
  public static readonly DeviceDetailModel DT852P = new DeviceDetailModel("852P","v3","v4");
  public static readonly DeviceDetailModel DT83P = new DeviceDetailModel("853P","v5","v6");
  public static readonly DeviceDetailModel DT854P = new DeviceDetailModel("854P");


 public string DeviceName { get; private set; }
 public string Value1 { get; private set; }
 public string Value2 { get; private set; }

 private DeviceDetailModel(string deviceName,string value1,string value2)
 {
  DeviceName = deviceName;
  Value1 = value1;
  Value2 = value2;
 }
}

now if i want to get a detail of single item its easy i just had to do DeviceDetailModel.DT854P

but the issue I would be getting a value on runtime using which I had to identify which struct property I had to return

eg = my runtime value is 853P I want to loop over my struct to identify where in DeviceName matched to this value 853P and which should return DeviceDetailModel.DT83P

I was able to loop over the properties of the struct but wasn't able to get value

Editing: Based on my run time value, i need to iterate over DeviceName's value and if the value matches it should return associated property

Upvotes: 2

Views: 46

Answers (1)

Zohar Peled
Zohar Peled

Reputation: 82474

Here's one fairly simple option:

public struct DeviceDetailModel
{
    private static readonly Dictionary<string, DeviceDetailModel> models = new Dictionary<string, DeviceDetailModel>
    {
        {"851P", new DeviceDetailModel("851P")},
        {"852P", new DeviceDetailModel("852P")},
        {"853P", new DeviceDetailModel("853P")},
        {"854P", new DeviceDetailModel("854P")},
    };

    public static DeviceDetailModel DT851P get => models["851P"];
    public static DeviceDetailModel DT852P get => models["852P"];
    public static DeviceDetailModel DT83P get => models["853P"];
    public static  DeviceDetailModel DT854P get => models["854P"];

    private DeviceDetailModel(string deviceName)
    {
        DeviceName = deviceName;
    }

    public string DeviceName {get;private set;}

    public DeviceDetailModel? FindByDeviceName(string deviceName)
    {
        return models.TryGetValue(deviceName, out var value) ? value : (DeviceDetailModel)null;
    }
}

Note that the return value of FindByDeviceName is a Nullable<DeviceDetailModel> so in case you're looking for a string that's not found you wont get an exception, but null.

Upvotes: 1

Related Questions