I have a linq statement similar to the following:
var entities = from row in table.AsEnumerable()
select new
{
ID = row.ID,
X = GetObjectByProcessingID(row.ID)[0],
Y = GetObjectByProcessingID(row.ID)[1],
....
};
Would it be possible to do something like:
var entities = from row in table.AsEnumerable()
select new
{
private var tmp = GetObjectByProcessingID(row.ID),
ID = row.ID,
X = tmp[0],
Y = tmp[1],
....
};
To avoid calling GetObjectByProcessingID twice?
I know you can do something like:
var entities = from row in table.AsEnumerable()
select new
{
ID = row.ID,
XAndY = GetObjectByProcessingID(row.ID),
....
};
But in this case, it will expose the whole array. I also know that I can implement stuff like caching on the method side (GetObjectByProcessingID) or creating a helper method to call it and remember the last value if the ID is the same. But is there a better way? Can I create temporary variables while creating the anonymous type?
Use the let
keyword like this:
var entities = from row in table.AsEnumerable()
let tmp = GetObjectByProcessingID(row.ID)
select new {
ID = row.ID,
X = tmp[0],
Y = tmp[1],
....
};
You can also try using method syntax
which is very favorite to me:
var entities = table.AsEnumerable()
.Select(row => {
var tmp = GetObjectByProcessingID(row.ID);
return new {
ID = row.ID,
X = tmp[0],
Y = tmp[1],
....
};
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With