I have two Linq queries
dTable.AsEnumerable()
.Where(s => Convert.ToString(s["OccpStat"]).ToLower().Equals("i"))
.ToList()
.ForEach(D => D.SetField("OccpStat", Convert.ToBoolean(1)));
dTable.AsEnumerable()
.Where(s => Convert.ToString(s["OccpStat"]) != ("True"))
.ToList()
.ForEach(D => D.SetField("OccpStat", Convert.ToBoolean(0)));
Basically it work with DataTable and change value of cell if cell is "I" then 1 if not "I" then 0
Is there any chance of somehow merging them into one LINQ and just insert some If statement to it instead of looping twice through the same table with two linq queries?
Provided sample loops four times through DataTable
: two times when calling ToList
, and two times when calling ForEach
.
The next approach can be used to rewrite two given LINQ queries into one, and it will loop two times through DataTable
:
dTable.AsEnumerable()
// First loop.
.ToList()
// Second loop.
.ForEach(D =>
{
string OccpStat = Convert.ToString(D["OccpStat"]);
if (OccpStat.ToLower().Equals("i"))
D.SetField("OccpStat", Convert.ToBoolean(1));
else
D.SetField("OccpStat", Convert.ToBoolean(0));
});
If you want to loop only once through DataTable
then you should declare your own ForEach
method and delete call to ToList
method:
public static void ForEach<T>(this IEnumerable<T> items, Action<T> action)
{
foreach (T t in items)
action(t);
}
...
dTable.AsEnumerable()
.ForEach(D =>
{
string OccpStat = Convert.ToString(D["OccpStat"]);
if (OccpStat.ToLower().Equals("i"))
D.SetField("OccpStat", Convert.ToBoolean(1));
else
D.SetField("OccpStat", Convert.ToBoolean(0));
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.