如何将值添加到列表<值对>对象</值对>

时间:2012-05-25 13:55:59

标签: c# asp.net

我有List<ValuePair>个对象:listUserRoleValuePair。我必须在foreach循环的列表中添加ixUsername作为我的值对。我怎么能添加这个?

List<ValuePair> listUserRoleValuePair = new List<ValuePair>();
var ixUserList= _mapper1.FindUserRoleLike(sName);
User result = null;

foreach (var ixUser in ixUserList)
{
    result = new UserMapper(connection).FindById(ixUser);
    var name = result.SFirstName + " " + result.SLastName;

    //listUserRoleValuePair.Add(ixUser);
    // listUserRoleValuePair.Add(    
}

我的ValuePair类如下

public class ValuePair
{
    private string _index;
    private string _sName;

    public ValuePair(string index, string sName)
    {
        _index = index;
        _sName = sName;
    }

    public string Index
    {
        get { return _index; }
        set { _index = value; }
    }

    public string SName
    {
        get { return _sName; }
        set { _sName = value; }
    }
}

6 个答案:

答案 0 :(得分:4)

您可以使用KeyValuePair类:

List<KeyValuePair<string,string>> listUserRoleValuePair = new List<KeyValuePair<string,string>>();

然后:

listUserRoleValuePair.Add(new KeyValuePair<string,string>(name, ixUser);

您也可以使用词典而不是列表。

答案 1 :(得分:2)

如果ixUser是索引字符串,请使用以下代码:

List<ValuePair> listUserRoleValuePair = new List<ValuePair>();
var ixUserList= _mapper1.FindUserRoleLike(sName);
User result = null;

foreach (var ixUser in ixUserList)
{
    result = new UserMapper(connection).FindById(ixUser);
    var name = result.SFirstName + " " + result.SLastName;
    listUserRoleValuePair.Add(new ValuePair(ixUser, name));
}

答案 2 :(得分:2)

listUserRoleValuePair.Add(new ValuePair(index, name));

我,不清楚对象的索引值是什么,但不管它是什么,只需在上面的行中替换它

答案 3 :(得分:2)

您只能添加支持子对象类型的项目,您可以使用其中一种。

collection.Add(new ValuePair(index, Name))

or
collection.Add(new ValuePair(){Index = index,SName= Name});

或非常简单的创建对象并传递为

Valuepair valpair = new ValuePair();
valpair.Index = index;
valpair.SName = name;

collection.Add(valpair);

答案 4 :(得分:1)

试试这个

var pair = new ValuePair();
// somehow intialize pair
listUserRoleValuePair.Add(pair);

答案 5 :(得分:1)

listUserRoleValuePair.Add(new ValuePair(ixUser, name));