How to extract refactoring properties

I have this property

public List<PointK> LineList
{get;set;}

Where PointKconsists of the following structure:

string Mark{get;set;}
double X{get;set;}
doible Y{get;set;}

Now I have the following code:

   private static Dictionary<string , double > GetY(List<PointK> points)
    {
        var invertedDictResult = new Dictionary<string, double>();
        foreach (var point in points)
        {
            if (!invertedDictResult.ContainsKey(point.Mark))
            {
                invertedDictResult.Add(point .Mark, Math.Round(point.Y, 4));
            }

        }

        return invertedDictResult;
    }


   private static Dictionary<string , double > GetX(List<PointK> points)
    {
        var invertedDictResult = new Dictionary<string, double>();
        foreach (var point in points)
        {
            if (!invertedDictResult.ContainsKey(point.Mark))
            {
                invertedDictResult.Add(point .Mark, Math.Round(point.X, 4));
            }

        }

        return invertedDictResult;
    }

How to restructure the above code?

+3
source share
1 answer

you can use

 private static Dictionary<string , double > GetCoordinate
                    (List<PointK> points, Func<Point, double> selector) 

    { 
        var invertedDictResult = new Dictionary<string, double>(); 
        foreach (var point in points) 
        { 
            if (!invertedDictResult.ContainsKey(point.Mark)) 
            { 
                invertedDictResult.Add(point.Mark, Math.Round(selector(point), 4)); 
            } 

        } 

        return invertedDictResult; 
    } 

and reduce your methods to

 private static Dictionary<string , double > GetX(List<PointK> points) 
    {         
        return GetCoordinate(points, p => p.X); 
    } 
+2
source

Source: https://habr.com/ru/post/1742999/


All Articles