C
C#2y ago
Dyad

❔ Create list from items and other lists

Whats the best way to create a new list that combines an item A, an item B, and a list C?
11 Replies
Dyad
DyadOP2y ago
something like?
var r = new []
{
new [] { A },
new [] { B },
C
}
.SelectMany(x => x);
var r = new []
{
new [] { A },
new [] { B },
C
}
.SelectMany(x => x);
Jimmacle
Jimmacle2y ago
you could use the .Concat extension method on the list C.Concat(new [] { A, B }) but if your goal is a new list then just copy the list and add the items
var newList = new List<MyObject>(C);
newList.Add(A);
newList.Add(B);
var newList = new List<MyObject>(C);
newList.Add(A);
newList.Add(B);
Dyad
DyadOP2y ago
I guess I should have clarified the order matters
Jimmacle
Jimmacle2y ago
then
var newList = new List<MyObject> { A, B };
newList.AddRange(C);
var newList = new List<MyObject> { A, B };
newList.AddRange(C);
Dyad
DyadOP2y ago
gotcha I often try to write my code in a way that declaration and assignment all happens in a single line I think in javascript you can do new [a, b, ...c], was hoping there was something similar in c#
Jimmacle
Jimmacle2y ago
nope, no spread operator in C#
Dyad
DyadOP2y ago
gotcha. thank you 🙂
Sun「無用」
spread operator is just sugar to what AddRange would be in c#
Jimmacle
Jimmacle2y ago
basically there's just no one-liner for this specific application
Thinker
Thinker2y ago
coming soon™!
Accord
Accord2y ago
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.
Want results from more Discord servers?
Add your server