Is there a pre-existing function that will return a set of numbers based on the base number and the "offset"?

I don't want to reinvent the wheel: if I want to get every integer in the range from N of a given number, what is the most efficient way to do this?

What I mean is something like this:

public List<int> getIntsWithinN(int BaseInt, int Offset) 

... so if the arguments passed in are 7 and 3, the result will be 4..10; if the arguments passed, there were 42 and 7, the result would be 35..49, etc.

UPDATE

Well, finally, I tried to implement this. But I don't know if I should pass my list to ToList () as follows:

 List<int> listInts = new List<int>(); . . . Enumerable.Range(lineNum - Offset, Offset * 2 + 1).ToList(listInts); 

... or do it like this:

 listInts = Enumerable.Range(lineNum - Offset, Offset * 2 + 1).ToList(); 

... but I need to do this several times, so the Intellisense description is not like what I really need. It says: "Creates ... a list ..."

But I do not want each of them to be created every time, I want to add to the existing list and, preferably, simultaneously ignore duplicates.

+6
source share
3 answers

preferably while ignoring duplicates

In this you have to consider HashSet<int> .

 var hashSet = new HashSet<int>(); hashSet.UnionWith(Enumerable.Range(lineNum - offset, offset * 2 + 1)); 

If you need a list, you can call ToList() on hashSet at the end. You can also sort it when converting to a list, because HashSet<T> stores the elements in undefined order.

 var list = hashSet.OrderBy(i=>i).ToList(); 
+1
source

I don't think there will be a function for this, but I think this is the shortest and easiest:

 Enumerable.Range(BaseInt - Offset, Offset * 2 + 1).ToList() 
+13
source

You can create methods like this:

 public static IEnumerable<int> getIntsWithinN(int BaseInt, int Offset) { return getIntsWithinN(Enumerable.Empty<int>(), BaseInt, Offset); } public static IEnumerable<int> getIntsWithinN(this IEnumerable<int> source, int BaseInt, int Offset) { return source.Concat(Enumerable.Range(BaseInt - Offset, Offset * 2 + 1)); } 

Used as follows:

 var myBigList = Extensions.getIntsWithinN(7, 3).getIntsWithinN(42, 7); 

And then depending on how you want from there, for example

 var withDupsRemoved = new HashSet<int>(myBigList); var withDupsRemoved = new HashSet<int>(myBigList).OrderBy(x => x).ToList(); 

If the insertion order of the ranges is important, but you do not want duplicates, you can make a list like this:

 var withDupsRemoved = new List<int>(); foreach (var i in myBigList) if (!withDupsRemoved.Contains(i)) withDupsRemoved.Add(i); 

If the performance of this becomes a problem, instead of using LINQ Concat, you can roll up your own class that stores range boundaries and when two or more are added, if there is overlap, ranges are adjusted accordingly.

+1
source

Source: https://habr.com/ru/post/917139/


All Articles