C#更好地循环列表并向新列表对象添加值

C#更好地循环列表并向新列表对象添加值,c#,C#,我想知道是否有人能给我展示一种更好的方式来编写下面的代码。 基本上,我在一个customerRecords列表中循环,计算点之间的距离,然后创建一个新对象CustomerDistancerRecord并将其添加到CustomerDistancerRecord列表中,然后返回列表。谢谢 public List<CustomerDistanceRecord> Distance(List<CustomerRecords> customerRecords) {

我想知道是否有人能给我展示一种更好的方式来编写下面的代码。 基本上,我在一个customerRecords列表中循环,计算点之间的距离,然后创建一个新对象CustomerDistancerRecord并将其添加到CustomerDistancerRecord列表中,然后返回列表。谢谢

    public List<CustomerDistanceRecord> Distance(List<CustomerRecords> customerRecords)
    {
        var customerList = new List<CustomerDistanceRecord>();
        foreach(var customer in customerRecords)
        {
            var calcaulatedDistance = CalculateDistance(customer);
            var customerDistanceRecord = new CustomerDistanceRecord()
            {
                UserId = customer.UserId,
                Name = customer.Name,
                DistanceFromOfficeLocation = calcaulatedDistance
            };
            customerList.Add(customerDistanceRecord);
        }
        return customerList;
    }

        private double CalculateDistance(CustomerRecords customer)
        {
            double theta = customer.Longitude - OfficeLocation.Longitude;
            double dist = Math.Sin(deg2rad(customer.Latitude)) * Math.Sin(deg2rad(OfficeLocation.Latitude)) 
                + Math.Cos(deg2rad(customer.Latitude)) * Math.Cos(deg2rad(OfficeLocation.Latitude)) * Math.Cos(deg2rad(theta));
            dist = Math.Acos(dist);
            dist = rad2deg(dist);
            dist = dist * 60 * 1.1515;
            dist *= 1.609344;
            return dist;
        }  
公共列表距离(列表客户记录)
{
var customerList=新列表();
foreach(客户记录中的var客户)
{
var CalculatedDistance=计算距离(客户);
var customerDistanceRecord=新customerDistanceRecord()
{
UserId=customer.UserId,
Name=customer.Name,
DistanceFromOfficeLocation=计算距离
};
customerList.Add(customerDistancerRecord);
}
返回客户列表;
}
私人双重计算状态(CustomerRecords客户)
{
双θ=customer.Longitude-OfficeLocation.Longitude;
double dist=Math.Sin(deg2rad(customer.Latitude))*Math.Sin(deg2rad(OfficeLocation.Latitude))
+Math.Cos(deg2rad(customer.Latitude))*Math.Cos(deg2rad(OfficeLocation.Latitude))*Math.Cos(deg2rad(theta));
dist=数学Acos(dist);
dist=rad2deg(dist);
dist=dist*60*1.1515;
dist*=1.609344;
返回距离;
}  

您可以使用以下LINQ表达式:

var customerList = customerRecords.Select(g => new CustomerDistanceRecord
        {
            UserId = g.UserId,
            Name = g.Name,
            DistanceFromOfficeLocation = CalculateDistance(g)
        }).ToList();

您可以使用以下LINQ表达式:

var customerList = customerRecords.Select(g => new CustomerDistanceRecord
        {
            UserId = g.UserId,
            Name = g.Name,
            DistanceFromOfficeLocation = CalculateDistance(g)
        }).ToList();

如果继续问这个问题可能会更好,因为它没有请求帮助来解决问题。谢谢,我不知道代码复查。如果继续问这个问题可能会更好,因为它没有请求帮助来解决问题。谢谢,我不知道代码复查