[英]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
应该具有属性userid
和userlevelbul
但我无法访问它们。
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
): 无论使用userLevel
与Dictionary<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.