我有一个BillingProvider类,其中包含索赔清单。另外,我有一个包含错误的索赔编号列表。我想排除有错误的声明,并且,如果任何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();

09-17 17:24