C#类型转换帮助

时间:2011-04-17 07:11:20

标签: c# list enumerable tolist

我有一个结构如下,

struct Location
{
    public int Row;
    public int Column;

    public Location(int row, int column)
    {
        this.Row = row;
        this.Column = column;
    }
}

我的功能如下,

public List<Location> getNeighboringLocations(int row, int column)
{
    int[,] array = new int[rows, columns];
    int refx = row;
    int refy = column;

    //var neighbours = from x in Enumerable.Range(refx - 1, 3)
    //                 from y in Enumerable.Range(refy - 1, 3)
    //                 where x >= 0 && y >= 0 && x < array.GetLength(0) && y < array.GetLength(1)
    //                 select new { x, y };
    var neighbours = from x in Enumerable.Range(0, array.GetLength(0)).Where(x => Math.Abs(x - refx) <= 1)
                 from y in Enumerable.Range(0, array.GetLength(1)).Where(y => Math.Abs(y - refy) <= 1)
                 select new { x, y };

    return neighbours.ToList();
}

我希望返回类型是位置列表我该怎么做? 在此先感谢

3 个答案:

答案 0 :(得分:2)

...

select new Location(x, y);

答案 1 :(得分:2)

var neighbours = from x in Enumerable.Range(0, array.GetLength(0)).Where(x => Math.Abs(x - refx) <= 1)
                             from y in Enumerable.Range(0, array.GetLength(1)).Where(y => Math.Abs(y - refy) <= 1)
                             select new Location( x, y );

return neighbours.ToList();

答案 2 :(得分:1)

不应该执行返回匿名类型的select new { x, y },而应该执行select new Location(x, y)