You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何过滤Person集合:仅保留含多个特定类型File的对象并返回该类型文件

Solution for Filtering Persons with Multiple Specific File Types

Got it, let's break down how to solve this problem. First, since the full File entity definition isn't provided, I'll assume it has a property like Type (could be a string or enum) to distinguish different file types—this is the key property we'll use for filtering.

Step-by-Step Implementation (C# with LINQ)

Here's a practical example that filters Person objects to only those with multiple (let's define "multiple" as 2 or more) of your target file type, and returns only those specific files in the result:

// Define your target file type (adjust based on actual File property)
string targetFileType = "Invoice"; // Replace with your specific type
int minimumFileCount = 2; // "Multiple" = at least 2 files

var filteredPersons = personList
    // First: Keep only persons who have enough of the target file type
    .Where(p => p.file != null && p.file.Count(f => f.Type == targetFileType) >= minimumFileCount)
    // Second: For qualifying persons, only keep the target file type in their file list
    .Select(p => new Person
    {
        id = p.id,
        name = p.name,
        file = p.file.Where(f => f.Type == targetFileType).ToList()
    })
    .ToList();

Key Notes:

  • Null Safety: The check p.file != null prevents null reference exceptions if a Person has no files at all.
  • Adjust "Multiple": Change minimumFileCount to whatever number you need (e.g., 3 if you want 3+ files).
  • Enum Support: If File.Type is an enum instead of a string, just replace "Invoice" with the enum value (e.g., FileTypes.Invoice).
  • Immutability: Using Select to create new Person objects avoids modifying the original list—this is a best practice to prevent unintended side effects.

Alternative: Modifying Original Objects (If Permitted)

If you don't mind altering the original Person instances (not recommended in most cases), you can simplify the code:

var filteredPersons = personList
    .Where(p => p.file != null && p.file.Count(f => f.Type == targetFileType) >= minimumFileCount)
    .ToList();

// Update each person's file list to only include the target type
foreach (var person in filteredPersons)
{
    person.file = person.file.Where(f => f.Type == targetFileType).ToList();
}

内容的提问来源于stack exchange,提问作者Guilherme Caixeta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:16:30