我有一个类 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/