I am trying to figure out to change the follow code to a Lambda to make it 1 – 2 lines…
Please Help me out if possible… not completely sure when Interfaces are involved how to do Lambdas.
// List of objects
// with list of interfaces inside
// with list of Strings inside each each interface type.
List<MyObject> list = new List<MyObject>();
MyObject mo = new MyObject();
mo.Name = "Blah";
MyAction action1 = new MyAction();
action1.recipients.Add("email1");
action1.recipients.Add("email2");
action1.recipients.Add("email3");
mo.Actions.Add(action1);
MyAction2 action2 = new MyAction2();
action2.recipients.Add("email1");
action2.recipients.Add("email3");
mo.Actions.Add(action2);
MyAction3 action3 = new MyAction3();
action3.recipients.Add("email2");
action3.recipients.Add("email4");
mo.Actions.Add(action3);
list.Add(mo);
List<string> resulting = new List<string>();
foreach (MyObject o in list)
{
foreach (IAction i in o.Actions)
{
if (i.GetType().Name == "MyAction")
{
MyAction a = (MyAction)i;
resulting.AddRange(a.recipients);
}
else if (i.GetType().Name == "MyAction2")
{
MyAction2 a = (MyAction2)i;
resulting.AddRange(a.recipients);
}
else if (i.GetType().Name == "MyAction3")
{
MyAction3 a = (MyAction3)i;
resulting.AddRange(a.recipients);
}
}
}
IEnumerable<string> done = resulting.Distinct();
string[] sarr = done.ToArray();
Assuming your interface
IActionhas a property ofrecipientsyou do not need the casts – if not, you should add this property toIAction. Then you can do(Also it really should be capitalized
Recipientsto stick with the naming conventions for properties).Alternatively, which makes it somewhat clearer, above can also be written as: