Reputation: 1194
i've the following linq query
foreach (var row in nodes.
Select(tr => tr.Elements("td")
.Select(td => td.InnerText.TrimEnd())
.ToArray()))
{
mydatatable.Rows.Add(row);
}
can i add elments to the array like arthmatic calculations inside the linq syntax based on the values of other array indecies, without having to loop another time?
for example the resultant array will look like ["xx","9.4",1.4"]
, i am trying to add another elment for example the multiplication of the second element by the third elment so it will look like ["xx","9.4","2","18.8"]
and for sure its in string format, so need to cast to double then multiply then again to string
Upvotes: 0
Views: 123
Reputation: 6444
You don't want an array in this situation. Consider IList<T>
and doing these calculations outside of LINQ
for performance, readability and access.
IList<int> rows = nodes.Select(tr => tr.Elements("td")).Select(td => Convert.ToInt32( td.InnerText.TrimEnd())).ToList();
rows.Add(rows[1] * rows[2]);
Note: I know that you perhaps don't have integers, for the purpose of example code I casted otherwise you can't multiply.
IList<string> strs = nodes.Select(tr => tr.Elements("td")).Select(td => td.InnerText.TrimEnd()).ToList();
var ints = strs.Select(str => str.TryGetInt()).Where(i => i.HasValue).Select(i => i.Value);
strs.Add((ints[0] * [ints[1]).ToString());
public static class Extensions
{
public static int? TryGetInt(this string item)
{
int i;
bool success = int.TryParse(item, out i);
return success ? (int?)i : (int?)null;
}
}
Upvotes: 1