c# - Create null instead of empty dictionary where IEnumerable has no data -


following linq code, here return dictionary<string,object>, while filling object value each string key internally fill dictionary<string,string>, fieldpropertymappingin code below

allcardcolumnmappingfieldpropertyentity                    .groupby(column => (column.fielddesc + column.outputcolumnid))                    .todictionary(groupelement => groupelement.key,                                  groupelement => (object)groupelement.select(currentelement =>                                  {                                     currentelement.fieldpropertymapping =                                      fieldpropertyentity                                      .where(field => field.outputcolumnid == currentelement.outputcolumnid)                                      .where(field => field.fielddesc == currentelement.fielddesc)                                      .todictionary(property => property.propertydesc, property => property.propertyvalue);                                  return currentelement;                                  }).firstordefault()); 

challenge have in current code cannot have currentelement.fieldpropertymapping null @ time if where clause find no matching record lead empty dictionary, have business requirement make null if empty. have done following modification fulfill condition, there's better way achieve in linq code, pointer / suggestion

modified code

allcardcolumnmappingfieldpropertyentity                    .groupby(column => (column.fielddesc + column.outputcolumnid))                    .todictionary(groupelement => groupelement.key,                                  groupelement => (object)groupelement.select(currentelement =>                                  {                                      list<designcardfieldproperty> localdesigncardfieldpropertyentity = fieldpropertyentity                                          .where(field => field.outputcolumnid == currentelement.outputcolumnid)                                          .where(field => field.fielddesc == currentelement.fielddesc).tolist();                                       if(localdesigncardfieldpropertyentity.any())                                         currentelement.fieldpropertymapping = localdesigncardfieldpropertyentity                                             .todictionary(property => property.propertydesc, property => property.propertyvalue);                                       return currentelement;                                  }).firstordefault()); 


Comments