C
C#3y ago
Bujju

Help with refactoring [Answered]

How could I simplify this?
var service = new RbService();

switch (fieldNum)
{
case 0:
service.Data.UserAccounts.Find(x => x.UserId == ctx.User.Id).Field1 = value;
await ctx.CreateResponseAsync("✅ Set the first field.", true);
break;
case 1:
service.Data.UserAccounts.Find(x => x.UserId == ctx.User.Id).Field2 = value;
await ctx.CreateResponseAsync("✅ Set the second field.", true);
break;
case 2:
service.Data.UserAccounts.Find(x => x.UserId == ctx.User.Id).Field3 = value;
await ctx.CreateResponseAsync("✅ Set the third field.", true);
break;
}

service.Data.Update();
var service = new RbService();

switch (fieldNum)
{
case 0:
service.Data.UserAccounts.Find(x => x.UserId == ctx.User.Id).Field1 = value;
await ctx.CreateResponseAsync("✅ Set the first field.", true);
break;
case 1:
service.Data.UserAccounts.Find(x => x.UserId == ctx.User.Id).Field2 = value;
await ctx.CreateResponseAsync("✅ Set the second field.", true);
break;
case 2:
service.Data.UserAccounts.Find(x => x.UserId == ctx.User.Id).Field3 = value;
await ctx.CreateResponseAsync("✅ Set the third field.", true);
break;
}

service.Data.Update();
5 Replies
phaseshift
phaseshift3y ago
Extract duplicate code The find stuff could be written once before switch Why have field 1,2,3 instead of a list/array?
Bujju
BujjuOP3y ago
It’s not actually a field 1, 2, and 3, those are just example names
phaseshift
phaseshift3y ago
They're all the same type, tho
Bujju
BujjuOP3y ago
Okay, I’ll do that. Thanks
Accord
Accord3y ago
✅ This post has been marked as answered!
Want results from more Discord servers?
Add your server