Reputation: 1899
Edit: This is an example program, I understand that there is a sum operator in linq. However, I was trying to ask specifically on how to pass the pointer to the property to do something complex with it, not necessarily this summing algorithm.
Lets say I have a class like this:
class Point
{
double x {get; set;}
double y {get; set;}
}
and in my main program I had 2 functions.
double function1(List<Point> PointList)
{
double sum = 0.0;
foreach(Point p in PointList)
{
sum += p.x;
}
return sum;
}
double function2(List<Point> PointList)
{
double sum = 0.0;
foreach(Point p in PointList)
{
sum += p.y;
}
return sum;
}
These functions are completely identical except one is summing the X values, the other is summing the Y values. Since these are so similar, I would like to combine them such that I basically pass in that List of Points, and something to identify that I want to do the X or the Y based calculation.
I know I could put in a switch statement and tell it whether it was the X or the Y based on an enum, or a number that is defined to tell it to do the X or the Y. If this was a normal function, I suppose I could use s delegate, but this is a property, so I'm not sure how that translates.
So how do I combine those functions into something like:
double bothFunctions(List<Point> PointList, var propertyToUse)
{
double sum = 0.0;
foreach(Point p in PointList)
{
sum += p.propertyToUse;
}
return sum;
}
Where propertyToUse points to either X or Y.
Upvotes: 3
Views: 3594
Reputation: 29813
The current solutions work great, but they assume either that your operation is sum
, or that you will have only two possible properties (X
and Y
).
If you want more freedom, you can do:
double function(List<Point> PointList, Func<Point, double> selector)
{
double sum = 0.0;
foreach (Point p in PointList)
{
sum += selector(p);
}
return sum;
}
Then you call it like this:
double sumX = function(PointList, p => p.X);
double sumY = function(PointList, p => p.Y);
you'll be able to write more complicated selectors, like:
double sumXY = function(PointList, p => p.X + p.Y);
Upvotes: 7
Reputation: 5607
You should look at using the Enumerable.Sum
extension method instead of writing your own.
var sumX = pointList.Sum(item => item.X);
var sumY = pointList.Sum(item => item.Y);
You will need to add using System.Linq;
if not already present in your code file.
Upvotes: 2
Reputation: 50835
I think you're making it too complicated. You can use a method like this:
double bothFunctions(List<Point> PointList, bool sumX)
{
double sum = 0.0;
foreach(Point p in PointList)
{
if (sumX)
sum += p.x;
else
sum += p.y;
}
return sum;
}
Or just use LINQ:
var ySum = pointList.Sum(e => e.y);
var xSum = pointList.Sum(e => e.x);
Upvotes: 0