【问题标题】:C# type conversion HelpC# 类型转换帮助
【发布时间】: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&lt;T&gt;。也可以yield return x.
  • @Brad Christie:我会这样做,但它可以改变客户端代码使用它的方式。我不想在这方面走得太远。

标签: c# list linq enumerable


【解决方案1】:

...

select new Location(x, y);

【讨论】:

    【解决方案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();
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-31
        • 2011-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-29
        • 2017-05-13
        • 1970-01-01
        相关资源
        最近更新 更多