繁体   English   中英

在Linq中从X,Y坐标加入项目

[英]Join Item from X,Y Coordinates in Linq

我有一个数据库,可将x,y坐标对表解构为特定的数据项。

Coordinate
{
   int X,
   int Y,
   int Value
}

如何将Linq中的这些坐标重新合并到表中? 如果数据库中有空格(用-表示)怎么办:

             Y
          0  1  2
          -------
    0  |  4  6  7
 X  1  |  9  -  7
    2  |  6  3  5

如何在linq中处理呢?

LINQ通常适用于处理结构化(一维)数据,例如数据库或XML文件,但是我认为当需要创建二维数据结构时,LINQ不会为您提供帮助。

如果您只想将数据加载到2D数组中,那么它可能比直接写入数据的方法好得多(使用LINQ的Max扩展方法来获取大小):

int[,] values =  
  new int[coords.Max(c => c.X) + 1, coords.Max(c => c.Y) + 1];
foreach(var c in coords) 
  values[c.X, c.Y] = c.Value;

如果您想反过来做-从2D数组生成坐标,则可以使用LINQ的Enumerable.Range生成2D数组的索引以及where选择包含一些实际值的元素:

var coords = from i in Enumerable.Range(0, coords.GetLength(0))
             from j in Enumerable.Range(0, coords.GetLength(1))
             let v = coords[i, j]
             where v != '-'
             select new { X = i, Y = j, Value = Int32.Parse(v) }

我假设您将坐标存储在IEnumerable类中。 然后,您可以编写扩展功能,例如

public static int ValueAt(this IEnumerable<Coordinate> enumeable, int X, int Y)
{
    Coordinate c = enumeable.Where(W=>W.x==X && W.y==Y).SingleOrDefault(); //works as long as their are no duplicate entries... 
    if(c==null){return ....;}  //Depends on how you want to handle nulls... may be return typr should be nullable<int> ?
    return c.Value;
}

然后可以调用坐标.ValueAt(1,0)等...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM