查找导航使用LINQ点的列表中选择所需的距离 [英] Find the distance required to navigate a list of points using linq

查看:142
本文介绍了查找导航使用LINQ点的列表中选择所需的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用LINQ给出二维点的IEnumerable,查找浏览假设点的所有点都访问了它们出现在列表中的顺序所需要的距离。

Using linq given a IEnumerable of two dimensional points, Find the distance required to navigate all points assuming the points are visited in the order they appear in the list.

我想我也许可以以某种方式使用.Aggregate<>功能,但无法弄清楚如何使它发挥作用。问题是聚合返回相同类型的列表,它是一个点我需要一个标量(双)。

I thought I might be able to somehow use the .Aggregate<> function but can't figure out how to make it work. The problem is the aggregate returns the same type as the list, which is a point I need a scalar (double).

如果使用LINQ这个问题不解决的,这将是有趣的,知道什么类的问题可以,哪些类别的问题不能使用LINQ解决。

If this problem is not solvable using linq, it would be interesting to know what class of problem can and what class of problem can not be solved using linq.

这是不是功课,但在个人项目中的必要步骤,以帮助我学习LINQ。

This is not homework but is a required step in a personal project to help me learn linq.

推荐答案

这是如果你使用(或复制)中的在.NET 4 提供邮编扩展方法:

This is much easier if you use (or replicate) the Zip extension method available in .net 4:

var distances = points.Zip(points.Skip(1), Distance);
double totalDistance = distances.Sum();

使用距离的方法:

using the Distance method:

double Distance(Point p1, Point p2)
{
    double dx = p1.X-p2.X;
    double dy = p1.Y-p2.Y;
    return Math.Sqrt( dx*dx+dy*dy );
}

<一个href="http://community.bartdesmet.net/blogs/bart/archive/2008/11/03/c-4-0-feature-focus-part-3-intermezzo-linq-s-new-zip-operator.aspx"相对=nofollow>巴特解释(并展示如何实现)压缩在他的博客:

static class Enumerable 
{ 
    public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> func) 
    { 
        var ie1 = first.GetEnumerator(); 
        var ie2 = second.GetEnumerator();

        while (ie1.MoveNext() && ie2.MoveNext()) 
            yield return func(ie1.Current, ie2.Current); 
    } 
}

这篇关于查找导航使用LINQ点的列表中选择所需的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆