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

I have a list <> of class "region" with two variables: "startLocation" and "endLocation". I would like to combine these two into a new sorted 2-dimensional array, where its fair location and integer representing its beginning or end.

For example, if there are three objects in the list with

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

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

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

I would like to get a sorted two-dimensional array (either a list or similar) similar to:

[3] [1]

[5] [1]

[5] [-1]

[7] [-1]

[8] [1]

[9] [-1]

(it is desirable that the coincidences add their two values โ€‹โ€‹together, so two separate 5 in the array will be combined in [5 0] ... but this is not too important)

I am currently using the usual forloop, going through each one at a time and adding them to the list one at a time. This implementation is rather slow because I work with large data sets, and I assume that there is a more elegant / fast way to do this through LINQ.

Any suggestions would be highly appreciated.

+6
c # linq
source share
2 answers

You will need to define a helper method that divides the region into 2 parts, and it is much easier to represent this using a new structure or 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}; } 

You can then use the following LINQ query to split them and sort them.

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

This is not a solution suitable for LINQ in anything other than intellectual exercise. The foreach will be as fast (in fact, most likely faster) than any cobblestone LINQ implementation.

As a side note, I assume you are using foreach , not for . If not, then you can significantly speed up the process by switching to the foreach .

 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 } 
0
source share

All Articles