C
C#

help

❔ Return IEnumerable backwards

IIce_trooper1/24/2023
Hey! I got a method which returns a specific collection depending of the parameter. Right now, I needed to add a method to return similar result, but Left.Lane collection should be returned in backward order. How can I do it in the more compact way (and without errors)?
IIce_trooper1/24/2023
Old, working method:
public IEnumerable<T_Road_Lanes_LaneSection_Lr_Lane> GetLanes (LaneSide side)
{
return side switch
{
LaneSide.Left => Left != null ? Left.Lane : Enumerable.Empty<T_Road_Lanes_LaneSection_Lr_Lane>(),
LaneSide.Right => Right != null ? Right.Lane : Enumerable.Empty<T_Road_Lanes_LaneSection_Lr_Lane>(),
LaneSide.Center => Center.Lane,
_ => throw new ArgumentOutOfRangeException(nameof(side), side, "This lane side is not a valid value.")
};
}
public IEnumerable<T_Road_Lanes_LaneSection_Lr_Lane> GetLanes (LaneSide side)
{
return side switch
{
LaneSide.Left => Left != null ? Left.Lane : Enumerable.Empty<T_Road_Lanes_LaneSection_Lr_Lane>(),
LaneSide.Right => Right != null ? Right.Lane : Enumerable.Empty<T_Road_Lanes_LaneSection_Lr_Lane>(),
LaneSide.Center => Center.Lane,
_ => throw new ArgumentOutOfRangeException(nameof(side), side, "This lane side is not a valid value.")
};
}
IIce_trooper1/24/2023
New, not working method (that method should return Left colleciton in reversed order:
Ddont1/24/2023
you could use .Reverse() on the collection i suppose?
IIce_trooper1/24/2023
Reverse will call another IEnumerable, it wouldn't be performent 😅
TThinker1/24/2023
unrelated but wtf is that type name T_Road_Lanes_LaneSection_Lr_Lane
AAnton1/24/2023
it being an IEnumerable is already bad for perf make a custom iterator if you care about that
IIce_trooper1/24/2023
External library type
IIce_trooper1/24/2023
I ended with something like this. I don't know how I can simplify this
IIce_trooper1/24/2023
but Reverse built-in method would call another unnecessary IEnumerable 😅
AAnton1/24/2023
if you make a custom iterator type it won't have to you can make the iterator reversed and also be a value type to avoid allocations if you're just going to foreach over it, it will be better
Eero1/24/2023
You're using enumerables in the first place. You can't possibly be concerned about perf
AAnton1/24/2023
yeah the functional features in c# are implemented in a way that's quite bad for both perf and memory it's intentionally made more dynamic
Eero1/24/2023
And what you have there sure can be simplified a good bit
Ddont1/25/2023
dude, com on...
IIce_trooper1/25/2023
I'm working in game dev, so yeah I'm not joking about performance ;p If I have a list, that is, an indexed collection then I don't want to unnecessarily call an additional IEnumerable to Reverse if I can do it in a more efficient way. I just want to write this in the more compact way. BTW I changed the above code to yield break instead of yield return null because of the error.
Eero1/25/2023
yeah again, if you actually did care about perf, you wouldn't use enumerables at all foreaching over an enumerable is incredibly costly something as simple as
IEnumerable<int> ints = new int[1];
foreach (int i in ints)
{
Console.WriteLine(i);
}
IEnumerable<int> ints = new int[1];
foreach (int i in ints)
{
Console.WriteLine(i);
}
becomes
IEnumerator<int> enumerator = ((IEnumerable<int>)new int[1]).GetEnumerator();
try
{
while (enumerator.MoveNext())
{
Console.WriteLine(enumerator.Current);
}
}
finally
{
if (enumerator != null)
{
enumerator.Dispose();
}
}
IEnumerator<int> enumerator = ((IEnumerable<int>)new int[1]).GetEnumerator();
try
{
while (enumerator.MoveNext())
{
Console.WriteLine(enumerator.Current);
}
}
finally
{
if (enumerator != null)
{
enumerator.Dispose();
}
}
Ddont1/25/2023
you're even throwing exceptions... how many times would this code be called per second? also, have you tested performance at least?
IIce_trooper1/25/2023
You're right that foreach is more costly than for, but I wouldn't say that so much. Anyway, I've used them here to use the deferred execution functionality 😅 This exeception... should be exception. I've made it there only to throw something if someone would add new LaneSide (which should not happen) and it wouldn't be supported here. This method could be called at least once per frame
Ddont1/25/2023
seems reasonable and collection size?
IIce_trooper1/25/2023
Reverse would make new allocation for a stack, then loop once over collection, and then again to use it. That's why I'm so reluctant to use the Reverse method When I code it myself it loops over collection only once and without any allocations. In that case the code is just quite long which I prefer to simplify :f Quite small (in the worst case max 16) So yeah, IEnumerable for small collection is not great. Still want to use deferred execution.
Ddont1/25/2023
to me spending time optimizing this seems overkill as of now the only way i personally could think of simplifying it would be going unsafe
Eero1/25/2023
it's hard to make any suggestions without more context
IIce_trooper1/25/2023
You're probably right. And I don't want to use unsafe hah. Last question, could this code above be more readable for other programmers? Should I rewrite something?
Eero1/25/2023
public IEnumerable<T_Road_Lanes_LaneSection_Lr_Lane> GetLanesAwayFromCenterOrder(LaneSide side)
{
return side switch
{
LaneSide.Left => Left?.Lane.Reverse<T_Road_Lanes_LaneSection_Lr_Lane>() ?? Enumerable.Empty<T_Road_Lanes_LaneSection_Lr_Lane>(),
LaneSide.Right => Right?.Lane.Reverse<T_Road_Lanes_LaneSection_Lr_Lane>() ?? Enumerable.Empty<T_Road_Lanes_LaneSection_Lr_Lane>(),
LineSide.Center => Enumerable.Repeat(Center.Lane[0], 1),
_ => // ...
};
}
public IEnumerable<T_Road_Lanes_LaneSection_Lr_Lane> GetLanesAwayFromCenterOrder(LaneSide side)
{
return side switch
{
LaneSide.Left => Left?.Lane.Reverse<T_Road_Lanes_LaneSection_Lr_Lane>() ?? Enumerable.Empty<T_Road_Lanes_LaneSection_Lr_Lane>(),
LaneSide.Right => Right?.Lane.Reverse<T_Road_Lanes_LaneSection_Lr_Lane>() ?? Enumerable.Empty<T_Road_Lanes_LaneSection_Lr_Lane>(),
LineSide.Center => Enumerable.Repeat(Center.Lane[0], 1),
_ => // ...
};
}
what was the issue with this?
Ddont1/25/2023
too slow
Eero1/25/2023
but i don't see how
MMODiX1/25/2023
Ice_trooper#2729
Reverse would make new allocation for a stack, then loop once over collection, and then again to use it. That's why I'm so reluctant to use the Reverse method When I code it myself it loops over collection only once and without any allocations. In that case the code is just quite long which I prefer to simplify :f
Quoted by
<@!654411275094327296> from #Return IEnumerable backwards (click here)
React with ❌ to remove this embed.
Eero1/25/2023
i don't understand i mean either way, you could
private IEnumerable<T...> LeftReverse
{
get
{
if (Left is null)
yield break;

// forr
}
}
private IEnumerable<T...> LeftReverse
{
get
{
if (Left is null)
yield break;

// forr
}
}
AAkseli1/25/2023
yield return forces an allocation anyways
AAccord1/26/2023
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Looking for more? Join the community!

Want results from more Discord servers?
Add your server
Recommended Posts
✅ Shorten inline switch with multiple passing valuesHi! Would there be a way to shorten this? In python, their pattern matching would have a simple `in ❔ Where to store hashed user passwordsI'm working on a really small project just to learn more about ASP.NET and DB stuff. I have a users ❔ Is there a way to remove brackets from empty methods?E.g. ```CS public MismatchedEnumLengthsException() : base("Length of values and enums are different.❔ compare two datessee below <:RoleAssociate:605486956700237856>hello can someone fix me please and also tell me why im dumbpublic class PlayerGUI : MonoBehaviour { public float playerMoveSpeed; public float pla❔ how to save text from TextBox to file?without save file window❔ I can't autocomplete on VS code :cI tried many ways to fix this but nothing works. Help!❔ Can I generalise this method?```CS public static IEnumerable<Enum> TransformIdToEnums(string value, params Type[] enums) { st❔ c# helphow can i make ipv6 altering application using c#❔ Cross-platform keyboard and mouse automation library wantedAnyone knows a .NET library that is on par with pyautogui? Specifically, waiting for a key to be preHow to change the icon for Android in a Maui/Blazor application?Net 7.0, latest visual studio preview. I have a simple (beginner) one page Maui/Blazor app that is ❔ EF Core Code-first relationshipsHi there, I am trying to create a coffee vending machine application. But, I can't quite work the re❔ Hello, postman tips on hitting API with external login page? I need to get the 'code' response❔ Hello, I would like to make a console with the command: Script (some script)if (TextBox.Text == "script" { run script }❔ help me plsmain. cs(7,0): error CS1525: Unexpected symbol 'if'❔ Reusing strings across classesThis is file 1 https://cdn.discordapp.com/attachments/987310138195054592/1067462232860004433/image0❔ UWP TreeView is not stretching to fill spaceTitle pretty much explains it all: I have a TreeView that's not stretching and stays 0px x 0px if t❔ Is there an easy way to serialize a Dictionary<string, string> to XML nodes?I'm writing a program that has to produce the following XML: ```xml <Attributes> <Color>red</Col✅ Could not load file or assembly 'StackExchange.RedisWhat causes these errors? How do I fix it? The project builds find on my windows machine. But runnin❔ Async function seems to continue running after returning.Hi there I'm doing a post request to a REST API. I can see that the callback is running in the conso