如何从字典类型列表中检索数据?

时间:2014-02-06 10:50:55

标签: c# list dictionary

我有一个列表,它有词典。现在我想要检索字典的所有值如何? 每当我尝试在列表中运行foreach时,它都不会在item.like

中显示类型Dictionary
foreach(Dictionary dict in products)

我曾经在java中这样做但我不能用C#做到为什么?什么是解决方案?

代码如下所示

List<Dictionary<String,String>> products=new List<Dictionary<String,String>>();
        products=loader.filterproductsbysubcat(subcat);

and here is the generated dictionary list

List<Dictionary<String, String>> productlist = new List<Dictionary<string, string>>();
        String qry = "select product_tbl.Id,product_tbl.brandid,product_tbl.gender,product_tbl.info,product_tbl.name,product_tbl.price,product_tbl.productcode,product_tbl.status,image_tbl.imagename,image_tbl.imagepath from product_tbl left join image_tbl on  product_tbl.Id=image_tbl.productid where product_tbl.subcat='"+subcategoryid+"'";
        dt = db.ConnectDataBaseReturnDT(qry);
        foreach (DataRow row in dt.Rows)
        {
            Dictionary<String, String> mydictionary = new Dictionary<string, string>();
            mydictionary.Add("id",row["Id"].ToString());
            mydictionary.Add("brandid", row["brandid"].ToString());
            mydictionary.Add("gender", row["gender"].ToString());
            mydictionary.Add("info", row["info"].ToString());
            mydictionary.Add("name", row["name"].ToString());
            mydictionary.Add("price", row["price"].ToString());
            mydictionary.Add("productcode", row["productcode"].ToString());
            mydictionary.Add("status", row["status"].ToString());
            mydictionary.Add("imagename", row["imagename"].ToString());
            mydictionary.Add("imagepath", row["imagepath"].ToString());
            productlist.Add(mydictionary);
        }
        return productlist;

2 个答案:

答案 0 :(得分:2)

您需要指定通用参数:

foreach(Dictionary<string, string> dict in products)

C#没有像Java这样的泛型的“原始类型”。

答案 1 :(得分:0)

您可以使用:

foreach(var item in products)
{
    var key = item.Key;
    var value = item.Value;
}