简体   繁体   中英

Join Item from X,Y Coordinates in Linq

I have a database that deconstructs an x,y coordinate pair table into specific dataitems.

Coordinate
{
   int X,
   int Y,
   int Value
}

How do I rejoin these coordinates in Linq into a table? What if there are empty spaces in the Database (denoted by - ):

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

How do I handle that in linq?

LINQ is generally good for working with structured (one-dimensional) data such as databases or XML files, but I don't think it will help you when you need to create two-dimensional data structure.

If you just want to load the data into a 2D array, than it probably cannot get much nicer than the direct way of writing it (using Max extension method from LINQ to get the size):

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;

If you want to do it the other way round - to generate coordinates from a 2D array, then you can use LINQ's Enumerable.Range to generate indices of the 2D array and where to select elements that contain some actual value:

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) }

I assume that you stored the coordinates in an IEnumerable class. Then you can write an extension function such as

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;
}

Then you can call coordinates.ValueAt(1,0) etc...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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