c# - LINQ to 对象过滤

标签 c# .net linq

我有一个类 BillingProvider,其中包含一个声明列表。另外,我有一份包含错误的 claim 编号列表。我想排除有错误的声明,如果任何 BillingProvider 下的所有声明都有错误,则也排除 BillingProvider。我已经创建了一个简化的情况模型。下面的 LINQ 查询排除了错误,但多次返回 BillingProvider。

class Program
{
    class BillingProvider
    {
        internal string TaxId { get; set; }
        internal List<Claim> Claims = new List<Claim>();
    }

    class Claim
    {
        internal int ClaimNumber { get; set; }
        internal string ClaimDescr { get; set; }
    }

    private static void Main()
    {
        var allBillingProviders = new List<BillingProvider>
        {
            new BillingProvider
            {
                TaxId = "123456789",
                Claims =  new List<Claim>
                {
                    new Claim {ClaimNumber = 1, ClaimDescr = "First Claim"},
                    new Claim {ClaimNumber = 2, ClaimDescr = "Second Claim"},
                    new Claim {ClaimNumber = 3, ClaimDescr = "Third Claim"}
                }
            },

            new BillingProvider
            {
                TaxId = "012345678",
                Claims = new List<Claim>
                {

                    new Claim{ClaimNumber = 4, ClaimDescr = "Fourth Claim"},
                    new Claim{ClaimNumber = 5, ClaimDescr = "Fifth Claim"},
                    new Claim{ClaimNumber = 6, ClaimDescr = "Sixth Claim"},
                    new Claim{ClaimNumber = 7, ClaimDescr = "Seventh Claim"},
                    new Claim{ClaimNumber = 8, ClaimDescr = "Eighth Claim"}
                }
            }
        };


        // Set up errors
        var errors = new List<int> {2, 5};  // Claims 2 and 5 have erros and should be excluded


        var bpClaims = (from b in allBillingProviders
                        from c in b.Claims
                        where (!errors.Contains(c.ClaimNumber))
                        select b).ToList();

        foreach (var bpc in bpClaims)
            Console.WriteLine("Count of claims in {0} is {1}", bpc.TaxId, bpc.Claims.Count);
        Console.ReadLine();
    }

最佳答案

我会分两步进行:

var bpClaims = 
    allBillingProviders.Select(x => new BillingProvider()
      {
        TaxId = x.TaxId,
        Claims = x.Claims.Where(c => !errors.Contains(c.ClaimNumber)).ToList()
      })
    .Where(x => x.Claims.Any())
    .ToList();

关于c# - LINQ to 对象过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29220390/

相关文章:

c# - 如何通过 Web API 跟踪断开连接的实体

c# - 使用 LINQ 选择数据到嵌套类

C# 简化字符串数组初始化

c# - 如何轻松初始化元组列表?

进程中的 C# 管道 Linux 命令输出

c# - 找不到命名空间 'Smo',尽管添加了引用

c# - 比较javascript中的两个字符串; ASP。净C#

.net - 带有 RX 扩展的 LINQ

c# - 输入字符串的格式不正确。将字符串转换为 double

c# - 如何在 ASP.NET Core 中注入(inject)泛型的依赖