As a fairly new C# programmer I am a unsure about when and how to best make use of LINQ (and also when to choose the expression method syntax vs. the query syntax). This question often comes up for me at work, because I heavily lean toward making full use of new language features and a functional style, while my colleagues seem to prefer a more conservative style. This means I have to think a lot about when using LINQ is actually worth it.
Now here is where the review part comes in. This is an anonymized piece of code that this question came up for, once coded in a LINQ style and once in imperative style. Which version do you believe is preferable from a readability / maintainability viewpoint?
void updateItems()
{
Items.Clear();
Items.AddRange(Widget.GetDetectedWidgets()
.Intersect(GetRelevantWidgets())
.Select(widget => readSerialNr(widget))
.Where(serial => serial != null)
.DefaultIfEmpty("No relevant widgets found.")
.ToArray());
}
void updateItems()
{
Items.Clear();
List<string> relevantWidgets = GetRelevantWidgets().ToList();
foreach(string widget in Widget.GetDetectedWidgets())
{
if(relevantWidgets.Contains(widget))
{
string serial = readSerialNr(widget);
if(serial != null)
Items.Add(serial);
}
}
if(Items.Count == 0)
Items.Add("No relevant widgets found.");
}