Convert this code to LINQ?
Sorry, Im just picking up LINQ and am relatively new at it.
Is it possible to convert the following into LINQ?
foreach (DataRow row in results.Rows)
{
if (row["RE开发者_Go百科MARKS"].ToString() == "Passes" || row["REMARKS"].ToString() == "Promoted")
{
result = String.Concat(result,row["ROLL_NO"].ToString()," ");
}
}
We don't know what the initial value of result
is which makes this tricky, but assuming you actually just want a space-separated list, I'd do this:
var query = from DataRow row in result.Rows
let remarks = row["REMARKS"].ToString()
where remarks == "Passes" || remarks == "Promoted"
select row["ROLL_NO"].ToString();
string results = string.Join(" ", query);
(Note that DataTable
doesn't implement IEnumerable<DataRow>
, which is why I've used an explicitly typed range variable. An alternative would be to call result.Rows.AsEnumerable()
and make row
implicitly typed.)
The final line is assuming .NET 4, which has more overloads for string.Join
than earlier versions. Otherwise, this would do it:
string results = string.Join(" ", query.ToArray());
Of course, if you're using LINQ then you may well want to move away from DataTable
etc to start with and use LINQ to SQL, Entity Framework, nHibernate or any of the other options available :)
results.Rows
.Cast<DataRow>() // If you need this line or not depends on the type of result.Rows
.Where(row => row["REMARKS"].ToString() == "Passes" ||
row["REMARKS"].ToString() == "Promoted")
.Aggregate(result, (acc, row) => String.Concat(acc, row["ROLL_NO"].ToString()," "))
result = results.Rows.Cast<DataRow>().Where(row => row["REMARKS"].ToString() == "Passes" || row["REMARKS"].ToString() == "Promoted").Aggregate(result, (current, row) => String.Concat(current, row["ROLL_NO"].ToString(), " "));
string.Join(" ", result.Rows.Cast<DataRow>().Where(r => r["REMARKS"].ToString() == "Passes" || r["REMARKS"].ToString() == "Promoted").Select(r => r["ROLL_NO"].ToString()).ToArray());
精彩评论