1

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 ?

mohammad
  • 1,018
  • 2
  • 14
  • 27
  • 5
    It really doesn't help that you've posted pseudo-code instead of *real* code. As that's not your real code, we can't be sure that there isn't something important in your real code that you've left out. Please provide a [mcve]. But unless you care about the order, you can probably just use `var names = db.Customers.Where(u => browsers.Contains(u.BrowserName)).Select(u => u.FirstName).ToList();`. (You shouldn't call `db.Customers.ToList()` in general, as that will pull *all* the customers from the database...) – Jon Skeet May 13 '17 at 07:20
  • I'm not sure it is a total duplicate as flagged by @CodeCAsterYou can replace your `for` loop with this: `names.AddRange(users.where(x => browsers.Contains(x.BrowserName)).Select(x => x.FirstName));` – Frank Fajardo May 13 '17 at 07:36
  • @FrankFajardo: Nope, that wouldn't compile. – Jon Skeet May 13 '17 at 07:37
  • I'm not sure the SO item marked as duplicate of this is correct, or is answering this question. – Frank Fajardo May 13 '17 at 07:44
  • 2
    @FrankFajardo: The accepted answer definitely doesn't provide the most idiomatic way of using LINQ to create a list though, which is what the OP is trying to do. I don't think it's actually a *useful* duplicate in this case, so I've reopened. But the OP should definitely edit the question to be better... – Jon Skeet May 13 '17 at 08:03

2 Answers2

3

Instead of

for(var i = 0; i < browsers.lenght; i++) {
    names.Add(users.where(x => x.BrowserName == browsers[i]).FirstName);
}  

Use this

names = users.Where(x => browsers.Contains(x.BrowserName)).Select(y => y.FirstName).ToList();
OmG
  • 18,337
  • 10
  • 57
  • 90
1

You can do it by foreach like the following:

browsers.ToList().Foreach(x => users.where(y => y.BrowserName == x).ToList().Foreach(z => names.Add(z.FirstName)))
OmG
  • 18,337
  • 10
  • 57
  • 90