如何过滤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 != nullprevents null reference exceptions if a Person has no files at all. - Adjust "Multiple": Change
minimumFileCountto whatever number you need (e.g., 3 if you want 3+ files). - Enum Support: If
File.Typeis an enum instead of a string, just replace"Invoice"with the enum value (e.g.,FileTypes.Invoice). - Immutability: Using
Selectto create newPersonobjects 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
相关产品推荐
相关产品推荐

