0

I have the below dynamic array

dynamic[] queueList = await queueInfo.Run.GetData<dynamic[]>(Name);

enter image description here

I want to get the unique values present in ImportTableName field. So, after some search I found this,

var distNames = queueList.Select(o => new {o.ImportTableName }).Distinct();

enter image description here

which works as expected.

But I don't want to hard code the fieldname "ImportTableName". So tried doing something like this

dynamic[] queueList = await queueInfo.Run.GetData<dynamic[]>(Name);
string tableName = "ImportTableName"
var distNames = queueList.Select(o => new {o.tableName }).Distinct();

But it doesn't work, result is just NULL. Can someone help me to achieve this ?

Pரதீப்
  • 91,748
  • 19
  • 131
  • 172
  • The second way you tried that is hard coded not the first one which worked. In first method that is property of that class and second one is hard-coded string. – Tech Yogesh Oct 17 '18 at 05:54
  • @TechYogesh - I think I did not explain it properly, it is not always "ImportTableName", it can be anything. – Pரதீப் Oct 17 '18 at 05:56
  • 1
    Dynamic select https://stackoverflow.com/questions/16516971/linq-dynamic-select than just a `Distinct` after that. – Magnus Oct 17 '18 at 06:02
  • Dynamic is not a good fit when you don't know the property names at compile time. Have you considered storing your data in dictionaries instead? – Jonas Høgh Oct 17 '18 at 06:28
  • 1
    In order to answer this, we need to know how the dynamic objects are generated inside the GetData method. Using reflection works for regular .Net objects assigned to a dynamic reference, but not for e.g. ExpandoObjects. See https://stackoverflow.com/questions/4939508/get-value-of-c-sharp-dynamic-property-via-string – Jonas Høgh Oct 17 '18 at 07:03
  • 1
    what is the result of queueList.Select(o => o.GetType()) ? – alexqc Oct 17 '18 at 07:17
  • @alexqc - it returns `{Name = "JObject" FullName = "Newtonsoft.Json.Linq.JObject"}` – Pரதீப் Oct 17 '18 at 11:11

2 Answers2

2

As it is array of JObject, which has indexer, you can apply it to each element to get value of desired field:

var distNames = queueList.Select(x => x[tableName]).Distinct().ToList();
Slava Utesinov
  • 13,410
  • 2
  • 19
  • 26
1

My solution is:

    dynamic[] queueList = new dynamic[]{new { id = 1, ImportTableName = "Data"}};

    string propName = "ImportTableName";    
    var distNames = queueList.Select(d => d.GetType().GetProperty(propName).GetValue(d, null)).Distinct();

It returns as expected "Data".

alexqc
  • 547
  • 4
  • 9