What I understood, in the opposite of James & techloverr, you want to keep records with parameter null:
foreach (Menu menuBE in lstMenus){
if (menuBE.Parameters.Length > 0){
dynamic menu = new{
menuBE.MenuID,
menuBE.ParentMenuID,
menuBE.LinkText,
menuBE.ScreenName,
menuBE.Parameters,
menuBE.URL
};
}
else {
dynamic menu = new{
menuBE.MenuID,
menuBE.ParentMenuID,
menuBE.LinkText,
menuBE.ScreenName,
menuBE.URL
};
}
menus.Add(menu);
}
** UPDATE **
As I understand in the whole question, you do not want a property Parameters
when source data have Parameters.Lenght == 0, and that's why you are using dynamic type.
It's different from "that's OK have a property 'Parameters = null'". If that's the approach, you don't need to use dynamic type. Just add items as list-item of a declarated strong-type variable or list-item of anonymous type.
With the dynamic
type you add properties at declaration time. So, you have to separate the different assigns as the code above.
If you want to put if
outside to avoid duplicate code, you use ExpandoObject:
var m = new List<System.Dynamic.ExpandoObject>();
foreach (string item in new string[] { "a", "b", "c" }) {
dynamic menuItem = new System.Dynamic.ExpandoObject();
menuItem.pos1 = item;
menuItem.pos2 = (item == "b" ? item : null); // wrong
if (item == "c") { // correct
menuItem.pos3 = "I am at third iteration";
}
m.Add(menuItem);
}
See, if you put a breakpoint at m.Add(menuItem);
these are the results:
case item == "a":
menuItem.pos1 = "a";
menuItem.pos2 = null; // wrong: pos2 must not exists
case item == "b":
menuItem.pos1 = "b";
menuItem.pos2 = "b";
case item == "c":
menuItem.pos1 = "c";
menuItem.pos2 = null; // wrong: pos2 must not exists
menuItem.pos3 = "I am at third iteration"; // correct: pos3 only exists here.