Iterating Through a List and Conditionally Setting a Member - Comparison Of Approaches
I have a requirement to iterate through a list, and conditionally set a data item against each item in the collection:
Using the standard foreach
iterator, this is trivial:
//standard iteration
foreach (LogFileDataItem lfd in logFileData)
{
if (lfd.FileName.Equals(currentLine, StringComparison.OrdinalIgnoreCase))
{
lfd.SQLScriptExecuted = true;
}
}
But it got me into thinking that this was an ideal opportunity to explore LINQ, so I refactored to above to:
foreach (LogFileDataItem lfd in
from logFileDataItem in logFileData
where logFileDataItem.FileName.Equals(currentLine, StringComparison.OrdinalIgnoreCase)
select logFileDataItem)
{
lfd.SQLScriptExecuted = true;
}
Which, of course can be refactored into a lambda expression:
foreach (LogFileDataItem lfd in log开发者_如何学编程FileData.Where(item => item.FileName.Equals(currentLine, StringComparison.OrdinalIgnoreCase))
.Select(item => item))
{
lfd.SQLScriptExecuted = true;
}
So my question really is really, how different are they? Do any offer a significant advantage over any other?
Well, you can get rid of the "Select(item => item)" bit from the lambda version (as indeed the C# compiler would have done):
foreach (LogFileDataItem lfd in logFileData.Where(item =>
item.FileName.Equals(currentLine, StringComparison.OrdinalIgnoreCase))
But basically, yes - they're all doing the same thing. I'd consider separating out the query from the foreach loop:
var relevantLogItems = logFileData.Where(...);
foreach (var lfd in relevantLogItems)
{
...
}
but again that won't actually change what occurs.
精彩评论