【发布时间】:2011-08-07 05:18:11
【问题描述】:
我有一个结构如下,
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();
}
我希望返回类型是位置列表,我该怎么做? 提前致谢
【问题讨论】:
-
您应该避免使用 List
作为您的公共界面的一部分。尝试 IList 以获得相同的效果,但随着代码的增长,灵活性会更好。 -
neighbours.ToList().ForEach(Console.WriteLine);只是打印我需要的值,但我需要然后存储在 Location Struct 中如何?
-
@GregC:甚至可以说是
IEnumerable<T>。也可以yield return x. -
@Brad Christie:我会这样做,但它可以改变客户端代码使用它的方式。我不想在这方面走得太远。
标签: c# list linq enumerable