Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write this loop as a single line?

I don't know this is possible or not but let me ask you. How do I write the below loop in a shorter way using, for example, LINQ?

DataSet dsAllMonsters 
List<string> lstAllMonsters

for (int i = 0; i < dsAllMonsters.Tables[0].Rows.Count; i++)
{
    lstAllMonsters.Add(dsAllMonsters.Tables[0].Rows[i]["pokemonId"].ToString());
}
like image 584
MonsterMMORPG Avatar asked Feb 19 '23 10:02

MonsterMMORPG


2 Answers

I think it could.

lstAllMonsters = dsAllMonsters.Tables[0].Rows
   .Cast<DataRow>()
   .Select(r => r["pokemonId"].ToString())
   .ToList();
like image 129
Daniel A. White Avatar answered Feb 20 '23 22:02

Daniel A. White


Yes, it can be done in one line:

lstAllMonsters = dsAllMonsters.Tables[0].Rows.Cast<DataRow>().Select(row => row["pokemonId"].ToString()).ToList();

But sometimes two lines are better than one. I think you will find this more readable:

var rows = dsAllMonsters.Tables[0].Rows.Cast<DataRow>();
lstAllMonsters = rows.Select(row => row["pokemonId"].ToString()).ToList();
like image 21
Mark Byers Avatar answered Feb 20 '23 23:02

Mark Byers