I don't want to reinvent the wheel: If I want to get every integer within a range of N from a given number, what is the most efficient way to do it?
What I mean is something like this:
public List<int> getIntsWithinN(int BaseInt, int Offset)
...so that if the args passed in were 7 and 3, the result would be 4..10; if the args passed in were 42 and 7, the result would 35..49, etc.
Okay, I've finally gotten around to trying to implement this. But I don't know if I should pass my List to the ToList() like so:
List<int> listInts = new List<int>();
. . .
Enumerable.Range(lineNum - Offset, Offset * 2 + 1).ToList(listInts);
...or do it like so:
listInts = Enumerable.Range(lineNum - Offset, Offset * 2 + 1).ToList();
...but what I need to do is call this several times, so the Intellisense description doesn't seem like what I really need. It says, "Creates a ... List..."
But I don't want a new one to be created each time, I want to append to an existing list, and preferably simultaneously disregarding duplicates.
I don't think there's going to be a function for exactly this, but I think this is the shortest and simplest:
Enumerable.Range(BaseInt - Offset, Offset * 2 + 1).ToList()
preferably simultaneously disregarding duplicates
In that you should consider HashSet<int>
.
var hashSet = new HashSet<int>();
hashSet.UnionWith(Enumerable.Range(lineNum - offset, offset * 2 + 1));
If you want a list, you can call ToList()
on hashSet
in the end. You might also want to sort it when converting to list, since HashSet<T>
keeps the items in an undefined order.
var list = hashSet.OrderBy(i=>i).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With