使用Lambda表达式在接口列表中的列表内拉出一个不同的字符串列表等

时间:2012-01-26 16:24:50

标签: c# list lambda

我试图找出将关注代码更改为Lambda以使其为1 - 2行... 请尽可能帮助我......不完全确定何时涉及接口如何做Lambda。

        // 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();

1 个答案:

答案 0 :(得分:4)

假设您的界面IAction的属性为recipients,则不需要强制转换 - 如果不是,则应将此属性添加到IAction。然后就可以了

var sarr = list.SelectMany(o => o.Actions)
               .Select(x => x.recipients)
               .SelectMany(x => x)
               .Distinct()
               .ToArray()

(另外它应该大写Recipients以坚持属性的命名约定。

或者,这使得它更清晰,上面也可以写成:

var sarr = list.SelectMany(o => o.Actions.Select(x=> x.recipients))
               .SelectMany(x => x)
               .Distinct()
               .ToArray()