Keywords: C# | LINQ | String Matching | List Query | FirstOrDefault
Abstract: This paper provides an in-depth exploration of techniques for efficiently checking if a list contains elements with specific substrings and retrieving matching elements in C#. By comparing traditional loop methods with LINQ queries, it detailedly analyzes the usage scenarios and performance characteristics of LINQ operators such as Where and FirstOrDefault. Incorporating practical requirements like case-insensitive string comparison and multi-condition matching, it offers complete code examples and best practice recommendations to help developers master more elegant and efficient collection query techniques.
Problem Background and Requirements Analysis
In C# development practice, there is often a need to handle query operations on string lists, particularly checking whether the list contains elements with specific substrings and retrieving the complete element when found. This requirement is common in scenarios such as file processing, data filtering, and text search. Traditional solutions typically employ loop traversal, but this approach results in verbose code and lacks intuitiveness.
Limitations of Traditional Loop Methods
Developers initially attempted to use List.Contains and List.IndexOf methods, but these methods only perform exact match checks and cannot achieve partial string matching. The subsequent manual loop solution, while feasible, has the following shortcomings: poor code readability, need to manually handle boundary conditions, and limited extensibility—when more query conditions need to be added, the code becomes complex and difficult to maintain.
Advantages and Implementation of LINQ Queries
LINQ (Language Integrated Query) provides a more declarative query approach, allowing developers to express query intentions in a way closer to natural language. For partial string matching queries, the Where extension method can be used with Lambda expressions:
var matchingValues = myList
.Where(stringToCheck => stringToCheck.Contains(myString));This method returns a collection of all elements containing the target substring, suitable for scenarios requiring multiple matching results. If only the first matching item is needed, the FirstOrDefault method can be used:
var match = myList
.FirstOrDefault(stringToCheck => stringToCheck.Contains(myString));
if(match != null)
{
// Process the found matching element
}Advanced Application Scenarios and Optimization
In practical applications, there is often a need to handle more complex matching requirements. For example, case-insensitive string matching can be achieved as follows:
var match = myList.FirstOrDefault(item =>
item.IndexOf("targetString", StringComparison.OrdinalIgnoreCase) >= 0);For situations requiring checks against multiple substrings, multi-condition queries can be implemented by combining the Any method:
var searchStrings = new[] { "abc", "def", "ghi" };
var matches = myList.Where(item =>
searchStrings.Any(search => item.Contains(search)));Performance Analysis and Best Practices
From a performance perspective, LINQ queries have significant advantages in readability and maintainability, and their underlying implementations are highly optimized, with negligible performance loss. For large-scale data collections, it is recommended to: prefer FirstOrDefault over Where when only a single result is needed; consider using StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase for culture-insensitive string comparisons to improve performance; and for scenarios with extreme performance requirements, optimize using Parallel LINQ (PLINQ).
Practical Application Cases
In file processing scenarios, LINQ can be used to quickly filter filenames containing specific keywords:
var fileNames = new List<string>
{
"Report2023.pdf", "DataBackup.zip", "ProjectDocument.docx"
};
var documentFiles = fileNames
.Where(name => name.Contains("Document") || name.Contains("Report"))
.ToList();In data validation scenarios, it can quickly check if input contains illegal characters:
var forbiddenWords = new List<string> { "admin", "root", "system" };
var userInput = "UserAdministratorAccount";
var hasForbidden = forbiddenWords.Any(word =>
userInput.IndexOf(word, StringComparison.OrdinalIgnoreCase) >= 0);Summary and Recommendations
LINQ provides C# developers with powerful and flexible collection query capabilities, excelling particularly in partial string matching queries. By reasonably applying operators such as Where and FirstOrDefault, combined with Lambda expressions, developers can write query code that is both concise and efficient. It is recommended that developers actively adopt LINQ solutions in actual projects, while selecting appropriate string comparison methods and query strategies based on specific requirements to achieve optimal development efficiency and runtime performance.