我有一个班级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();
}
}
答案 0 :(得分:5)
我会分两步完成:
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();
答案 1 :(得分:1)
使用distinct的一种方法,但由于您可能希望通过ClaimNumber区分,因为我认为声明编号不会重复,您可以使用此库DistictBy
https://code.google.com/p/morelinq/
var bpClaims = (from b in allBillingProviders
from c in b.Claims
where (!errors.Contains(c.ClaimNumber))
select b).DistinctBy(c=>c.ClaimNumber).ToList();
答案 2 :(得分:1)
您可以通过在Console.WriteLine行中执行此操作来获取声明ID的计数,而不包括错误声明ID:
Console.WriteLine("Count of claims in {0} is {1}", bpc.TaxId, bpc.Claims.Select(x=> x.ClaimNumber).ToList().Except(errors).Count());