简体   繁体   中英

C# - Using LINQ to take two variables into a 2-dimensional array?

I have a list<> of an "region" class with two variables, "startLocation" and "endLocation". I'd like to combine those two into a new sorted 2 dimensional array where its just Location and an integer representing whether its start or an end.

For example, if the list has three region objects with

[Region 1] : startLocation = 5, endLocation = 7

[Region 2] : startLocation = 3, endLocation = 5

[Region 3] : startLocation = 8, endLocation = 9

I'd like to get a sorted two dimensional array (or list or similar) looking like:

[3] [1]

[5] [1]

[5] [-1]

[7] [-1]

[8] [1]

[9] [-1]

(preferably i'd like the overlaps to add their second values together, so the two separate 5's in the array would be combined into [5 0]...but that's not too important)

I'm currently using a regular forloop going through each one by one and adding them to a list one at a time. This implementation is quite slow because I'm working with large datasets, and I'm guessing there's a more elegant / faster way to accomplish this through LINQ.

Any suggestions would be much appreciated.

You'll need to define a helper method which splits a region into 2 parts and it's much easier to represent this using a new struct vs. a 2D array

struct Data {
  public int Value;
  public bool IsStart;
}

public static IEnumerable<Data> Split(this Region region) {
  yield return new Data() { Value = region.StartLocation, IsStart=true};
  yield return new Data() { Value = region.EndLocation, IsStart=false};
}

Then you can use the following LINQ query to break them up and sort them.

List<Region> list = GetTheList();
var query = list
  .SelectMany(x =>  x.Split())
  .OrderBy(x => x.Data);

This isn't a solution that's suitable for LINQ in anything other than an intellectual exercise. A foreach loop will be just as fast (actually likely faster) than any cobbled-together LINQ implementation.

As a side note, I'm assuming that you're using foreach rather than for . If not, then you could significantly speed up your process by switching to the foreach loop.

foreach(Region r in regionList)
{
    // add your entries using r
}

will be much faster than..

for(int i = 0; i < regionList.Count; i++)
{
    // add your entires using the indexer
}

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