0

I have the following Linq expression:

var itemToUpdate = ItemsUpdated.FirstOrDefault(x => x.Id == itemId);

I need to adapt it so that x.Id is a dynamically defined property, for example:

var itemToUpdate = ItemsUpdated.FirstOrDefault(x => x["Id"] == itemId);

I have tried the following already which I thought would be enough:

var itemToUpdate = ItemsUpdated.FirstOrDefault(x => (int)x.GetType().GetProperty("Id").GetValue(x) == itemId);

This runs without any errors, but any code after this statement does not execute therefore I assume something goes wrong with the expression above.

Jim G.
  • 15,141
  • 22
  • 103
  • 166
Musaffar Patel
  • 905
  • 11
  • 26
  • Which types could ’x["Id"]’ theoretically be? – Jim G. Nov 19 '22 at 00:27
  • @JimG. It is only ever an Integer – Musaffar Patel Nov 19 '22 at 00:28
  • 1
    In order to make this work, x would either have to be a dictionary, or a class instance having a defined indexer. – Robert Harvey Nov 19 '22 at 00:38
  • Does this answer your question? [Get property value from C# dynamic object by string (reflection?)](https://stackoverflow.com/questions/8631546/get-property-value-from-c-sharp-dynamic-object-by-string-reflection) – Jim G. Nov 19 '22 at 00:40
  • @Jim G. It doesn't unfortunately, I've already tried reflection but reflection only seems to work when I want to select, not when I use the property together with "==" comparison operator – Musaffar Patel Nov 19 '22 at 00:44
  • Does this answer your question? https://stackoverflow.com/a/66099661/109941 – Jim G. Nov 19 '22 at 00:44
  • @Jim G. Perhaps but I want to avoid deserializing and serializing seems like overkill, but perhaps I need to rethink this and find an alternative to implementing a dynamic property – Musaffar Patel Nov 19 '22 at 00:47
  • @RobertHarvey I'm interested in the possibility of using a Dictionary, could you show me how? – Musaffar Patel Nov 19 '22 at 01:06
  • 1
    There are several ways to accomplish some variation of what you're trying to do. It would be useful if we had more context. What problem are you trying to solve? See https://xyproblem.info. – Robert Harvey Nov 19 '22 at 15:00

0 Answers0