Home > Software engineering >  C# foreach list element in a list add a AddField
C# foreach list element in a list add a AddField

Time:11-13

I'm trying to create a discord bot which sends embed messages using the discord.net package.

This discord package brings a function to create embeds called EmbedBuilder which can be seen here: https://docs.stillu.cc/api/Discord.EmbedBuilder.html

The following function works great. The code looks like this:

public async Task ExampleAsync()
{
    var embedElement = new EmbedBuilder()
        .WithTitle("Example Name")
        .AddField("Working", "Example")
        .Build();

    var chnl = BotClient.GetChannel(123) as IMessageChannel;
    await chnl.SendMessageAsync(embed: embedElement);
}

But let's say I have a List containing users and I wanted to add a AddField("Working", "Example") for each user in my list how would I do this?

Because things like the following are clearly not working and I can't find any info on this.

public List<UserObject> Users;

public async Task ExampleAsync()
{
    var embedElement = new EmbedBuilder()
        .WithTitle("Example Name")
        foreach(UserObject user in Users) 
        {
            .AddField("Working", "Example")
        }
        .Build();

    var chnl = BotClient.GetChannel(123) as IMessageChannel;
    await chnl.SendMessageAsync(embed: embedElement);
}

I would appreciate any kind of help and suggestions.

CodePudding user response:

Try this:

public List<UserObject> Users;

public async Task ExampleAsync()
{
    var embedElement = new EmbedBuilder().WithTitle("Example Name");
    foreach(UserObject user in Users) 
    {
        embedElement.AddField("Working", "Example");
    }
    embedElement.Build();

    var chnl = BotClient.GetChannel(123) as IMessageChannel;
    await chnl.SendMessageAsync(embed: embedElement);
}
  • Related