This is probably easy for someone more experienced with LINQ and the Lambda expressions in C#. I'm just starting out with them, so I must be missing something.
I have a custom object like this:
public class BusinessName {
public string Name { get; set; }
public string Type { get; set; }
}
Then, I have a list of these objects:
List<BusinessName> businessNames = new List<BusinessName>();
I want to convert this into a list of string
with the Name
property of the BusinessName
object:
List<string> names = new List<string>();
Obviously, I could do this:
foreach (BusinessName name in businessNames) {
names.Add(name.Name);
}
But, I want to try using the lambda expressions with LINQ so that I can put this into a one liner.
So, I tried:
names.AddRange(businessNames.Select(item => item.Name));
This works as expected, but is much slower than the foreach loop by 2x. I suspect this is because it's iterating the list twice, unlike the foreach loop.
So, I started looking for an alternative. I found Concat()
but couldn't figure out how it was any different than AddRange()
.
Does anyone know a way to do this in one pass with LINQ?