I have a string array and a for loop to add items to list.
Here is my code:
//customers table :
// Firstname, Lastname, Age, BrowserName, Date
string[] browsers = {"chrome", "Firefox", "Edge"}
var users = db.customers.ToList();
list<string> names = new List<string>();
for(var i = 0; i < browsers.lenght; i++) {
names.Add(users.where(x => x.BrowserName == browsers[i]).FirstName);
}
Is there any way to use Linq method or something else instead of for ?
var names = db.Customers.Where(u => browsers.Contains(u.BrowserName)).Select(u => u.FirstName).ToList();. (You shouldn't calldb.Customers.ToList()in general, as that will pull all the customers from the database...)forloop with this:names.AddRange(users.where(x => browsers.Contains(x.BrowserName)).Select(x => x.FirstName));