关于List <t> </t>的问题

时间:2011-06-12 15:30:20

标签: c#

我有一个包含数据的列表:

public List<Client> AddClients( )
{
    List<Client> clients = new List<Client>();
    clients.Add(new Client()
    {
       Name = "MyName",
    });
    return clients;
}

我的问题是如何制作一个方法在同一个列表中添加新名称?

5 个答案:

答案 0 :(得分:2)

我不确定我理解你的问题。

您可以在返回列表中添加新名称。

例如

var myList = AddClients();

myList.Add(new Client()
    {
        Name = "NextName"
    });

您还可以更改客户端以接受名称数组以添加客户端。

public List<Client> AddClients(IEnumerable<string> names)
{
    List<Client> clients = new List<Client>();

    foreach(var name in names)
    {
        clients.Add(new Client()
        {
           Name = name,
        });
    }

    return clients;
}

然后将其称为

var myList = AddClients(new[] {"MyName", "NextName"});

// My list contains both MyName and NextName

答案 1 :(得分:1)

问题尚不清楚,但听起来你想做这样的事情:

public void AddClients(List<Client> clients, string name)
{
    clients.Add(new Client()
    {
       Name = name,
    });
    return clients;
}

答案 2 :(得分:0)

您的问题有点不清楚,但假设您要使用此方法将名称添加到列表中,则应将列表作为参数传递:

public List<Client> AddClients(List<Client> clients )
{
    clients.Add(new Client()
    {
       Name = "MyName",
    });
    return clients;
}

答案 3 :(得分:0)

如果你问我认为你在问什么(我根本不确定:)),那就试试这个:

public List<Client> AddClients( )
{
    List<Client> clients = new List<Client>();
    clients.Add(new Client()
    {
       Name = new Name("myname"),
    });
    return clients;
}

答案 4 :(得分:0)

您无法使用相同的方法传递其他名称。请参阅下面的修改方法,该方法接受您可以传递名称的字符串参数。

public List<Client> AddClients(string strName)
{
    List<Client> clients = new List<Client>();
    clients.Add(new Client()
    {
       Name = strName,
    });
    return clients;
}

然后你会打电话给

AddClients("MyName");
AddClients("MyName2")

相关问题