C
C#13mo ago
BenMcLean

LINQ to keep adding items until a fixed length is reached?

Let's say I have a LINQ collection of uint some length less than 256 and I want to keep adding 0u until it reaches length 256. If the length is already 256 or higher then this method should do nothing. Can I do that with LINQ? If so, what would be the method for that?
10 Replies
Angius
Angius13mo ago
What do you mean "LINQ collection"?
Denis
Denis13mo ago
The length as in element count? And I suppose you mean IEnumerable<uint>,.right?
BenMcLean
BenMcLeanOP13mo ago
right, element count yeah i think
W Sigma El Skibidi
I would check the length of the list and then simply loop until its 256
Denis
Denis13mo ago
Does it have to be an IEnumerable? It means that the sequence of elements is created on access - it is lazy accessed. Behind an IEnumerable you can either have a list behind it, or a database call. So better use a List<uint> directly
W Sigma El Skibidi
Im not sure if this is what ur looking for but this literally does that kekw
No description
W Sigma El Skibidi
this seems too easy of a fix so i may be Hmm
Angius
Angius13mo ago
Could try something like this maybe, playing with the properties if IEnumerable
IEnumerable<T> Pad<T>(this IEnumerable<T> elements, int length, T pad)
{
for (var i = 0; i < length; i++)
{
if (i < elements.Count())
{
yield return elements[i];
}
else
{
yield return pad;
}
}
}
IEnumerable<T> Pad<T>(this IEnumerable<T> elements, int length, T pad)
{
for (var i = 0; i < length; i++)
{
if (i < elements.Count())
{
yield return elements[i];
}
else
{
yield return pad;
}
}
}
Nah, that would enumerate the IEnumerable needlessly. I'm gonna have to test it some This seems to work looks like:
public static IEnumerable<T> PadTo<T>(this IEnumerable<T> elements, int count, T item)
{
var amount = 0;

foreach (var element in elements)
{
amount++;
yield return element;
}
for (var i = 0; i < count - amount; i++)
{
yield return item;
}
}
public static IEnumerable<T> PadTo<T>(this IEnumerable<T> elements, int count, T item)
{
var amount = 0;

foreach (var element in elements)
{
amount++;
yield return element;
}
for (var i = 0; i < count - amount; i++)
{
yield return item;
}
}
And no needless enumeration Usage:
var padded = [1, 2, 3].PadTo(5, 0); // [1, 2, 3, 0, 0]
var padded = [1, 2, 3].PadTo(5, 0); // [1, 2, 3, 0, 0]
PixxelKick
PixxelKick13mo ago
If you can work with an array/span you can do this way faster using Array.Copy
BenMcLean
BenMcLeanOP12mo ago
That's pretty good thanks Agreed but this is for situations where it would be a collection coming in
Want results from more Discord servers?
Add your server