How to write this loop as one line?

I do not know whether this is possible or not, but let me ask you. How to write a short cycle below 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()); } 
+4
source share
3 answers

I think it's possible.

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

Yes, this 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(); 
+4
source

Another way to achieve this in one line.

 dsAllMonsters.Tables[0].AsEnumerable().ToList().ForEach((DataRow a) => lstAllMonsters.Add(a["pokemonId"].ToString())); 
0
source

Source: https://habr.com/ru/post/1447503/


All Articles