如何使用LINQ匹配List1与List2.ListInfo的StudentCode并返回List1数据
First, let's clarify what we need: we want all List1 instances where their StudentCode exists in any ListInfo collection of any List2 object.
There are a couple of clean, practical ways to do this with LINQ, depending on whether you prioritize readability or performance (both work great for most common scenarios).
Method 1: Using a HashSet for Efficient Lookup
This approach first extracts all unique StudentCode values from the ListInfo collections, then filters List1 against that set. Checking membership in a HashSet is an O(1) operation, making this ideal if you're working with large datasets.
// First, collect all unique StudentCodes from List2's ListInfo collections var matchingStudentCodes = new HashSet<string>( list2.SelectMany(l2 => l2.ListInfo) .Select(li => li.StudentCode) .Where(sc => !string.IsNullOrEmpty(sc)) // Optional: filter out null/empty codes ); // Filter List1 to get items with a matching StudentCode var matchedList1Items = list1 .Where(l1 => matchingStudentCodes.Contains(l1.StudentCode)) .ToList();
Method 2: Direct LINQ Join
If you prefer a concise one-liner, you can use a join between List1 and the flattened ListInfo entries from List2. Note that if multiple ListInfo entries share the same StudentCode, you might get duplicate List1 items—adding .Distinct() fixes this if needed.
var matchedList1Items = list1 .Join( list2.SelectMany(l2 => l2.ListInfo), // Flatten all ListInfo into a single sequence l1 => l1.StudentCode, // Match key from List1 li => li.StudentCode, // Match key from ListInfo (l1, li) => l1 // Return the matching List1 item ) .Distinct() // Optional: remove duplicate List1 entries .ToList();
Quick Notes:
- Both methods use case-sensitive matching by default. For case-insensitive checks, you can adjust the HashSet constructor (e.g.,
new HashSet<string>(StringComparer.OrdinalIgnoreCase)) or use an overload ofJointhat accepts a comparer. - The
Where(sc => !string.IsNullOrEmpty(sc))line is a defensive check to avoid matching null/empty codes—feel free to omit it if your data guarantees validStudentCodevalues.
内容的提问来源于stack exchange,提问作者Suresh Sankar

