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 ?

5
  • 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 minimal reproducible example. 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...) Commented May 13, 2017 at 7: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)); Commented May 13, 2017 at 7:36
  • @FrankFajardo: Nope, that wouldn't compile. Commented May 13, 2017 at 7:37
  • I'm not sure the SO item marked as duplicate of this is correct, or is answering this question. Commented May 13, 2017 at 7: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... Commented May 13, 2017 at 8:03

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

Comments

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)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.