简体   繁体   English

清单 <Dictionary> foreach获得价值

[英]List<Dictionary> foreach get value

List<Dictionary<string, object>> data = new List<Dictionary<string, object>>();
Dictionary<string, Object> objs = new Dictionary<string, object>();
for (int i = 1; i <= onlineolanlar.Count; i++)
{
    objs.Add(i.ToString(), new userLevel() { UserID = userID.ToString(), Presence = UserLevelBul.ToString() });
}
foreach (var item5 in objs.Values)
{
    //How can I access item5 properties here??
}

Hi all, 大家好,

How can I reach the values of that foreach loop? 我如何达到该foreach循环的值?

item5 should have properties userid and userlevelbul but I can't reach them. item5应该具有属性useriduserlevelbul但我无法访问它们。

You declared your dictionary objs as Dictionary<string, object> . 您将字典objs声明为Dictionary<string, object> But in fact you only want to add (and later use) entries of type userLevel . 但是实际上,您只想添加(和以后使用)类型userLevel条目。

So simply declare the dictionary with the correct types: 因此,只需使用正确的类型声明字典:

Dictionary<string, userLevel> objs = new Dictionary<string, userLevel>();

Then you can use it straight forward: 然后,您可以直接使用它:

foreach (var item5 in objs.Values)
{
     Console.WriteLine(item5.userID)
     Console.WriteLine(item5.Presence)
}

because now the elements in objs.Values as well as item5 are of type userLevel . 因为现在objs.Values以及item5中的元素都属于userLevel类型。

Either use userLevel with your Dictionary<string, Object> instead of Object or use Explicit casting (if you for some reason can't change object ): 无论使用userLevelDictionary<string, Object> ,而不是Object或使用显式转换 (如果你因为某些原因不能改变object ):

foreach (var item5 in objs.Values)
{
     string userId = ((userLevel)item5).UserID;
     // or
     // string userId = (item5 as userLevel).UserID;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM