过滤一个集合中的项目,这些项目在另一个集合中不存在 - LINQ方式

时间:2017-03-10 10:47:40

标签: c# performance linq

目前我正在寻找有效的解决方案来解决如何使用linq过滤一个集合中不存在于其他集合中的项目。 到目前为止,我提出了以下选项:

class ConrolAccount
        {
            public string ControlName { get; set; }

            public string NaturalAccount { get; set; }
        }

        static void Main(string[] args)
        {
            var defaultAccounts = new List<ConrolAccount>
            {
                new ConrolAccount {NaturalAccount = "71300", ControlName = "Income Control"},
                new ConrolAccount {NaturalAccount = "70900", ControlName = "AP Control"},
                new ConrolAccount {NaturalAccount = "71600", ControlName = "Cost Control"},
                new ConrolAccount {NaturalAccount = "20200", ControlName = "Trust Control"},
                new ConrolAccount {NaturalAccount = "71800", ControlName = "Tax Control"},
                new ConrolAccount {NaturalAccount = "72000", ControlName = "Undeposited Funds"}
            };

            var existingAccounts = new List<ConrolAccount>
            {
                new ConrolAccount {NaturalAccount = "70900", ControlName = "AP Control"},
                new ConrolAccount {NaturalAccount = "71600", ControlName = "Cost Control"},
                new ConrolAccount {NaturalAccount = "72000", ControlName = "Undeposited Funds"}
            };

            IEnumerable<string> missedAccounts = defaultAccounts
                .GroupJoin(existingAccounts, d => d.ControlName, e => e.ControlName, (d, accounts) => new {d, accounts})
                .Where(a => !a.accounts.Any())
                .Select(a => a.d.ControlName);

            foreach (string controlName in missedAccounts)
            {
                Console.WriteLine(controlName);
            }

            Console.WriteLine();
        }

这将输出:

  

收入控制   信任控制   税控

以下是沙箱的链接:http://rextester.com/EBLZ71941

使用linq可以提高效率吗?或者有人可以建议更快的算法而不使用linq?

2 个答案:

答案 0 :(得分:1)

由于您只对ControlName属性感兴趣,Except会更有效:

IEnumerable<string> missedAccounts = defaultAccounts.Select(a => a.ControlName)
    .Except(existingAccounts.Select(a => a.ControlName));

答案 1 :(得分:0)

您是否了解Intersect()Except()预定义函数?

Intersect() - 在两个列表/集合之间找到公共项目

Except() - 找到第一个集合中的项目以外的项目(按订单定义)