我有一个公共方法,它返回项的键和值的集合,我想输出特定的键值。以下是我正在使用的方法
public List<string> GetAll(string itemSystemname)
{
return itemValues[itemSystemname].Select(x => x.Value).ToList();
}
所有值都是使用foreach打印出来的
foreach (var item in i.GetAll("FrontPageNewsLarge"))
{
@item
}
OutPut:
Name,
address,
phone,
city,
Name,
address,
phone,
city
我想要超越价值的愿望就像这样
foreach (var item in i.GetAll("FrontPageNewsLarge"))
{
@item.getvalue("name") // OR item["ID"]
}
OutPut:
Name,
Name
ItemValues就像这样启动。
public class ItemRepository
{
public Dictionary<string, HashSet<KeyValuePair<string, string>>> itemValues = new Dictionary<string, HashSet<KeyValuePair<string, string>>>();
public ItemRepository(ItemCollection items)
{
// populate fields
foreach (var itemnames in items)
{
if (!itemValues.ContainsKey(itemnames.SystemName))
itemValues.Add(itemnames.SystemName, new HashSet<KeyValuePair<string, string>>());
var nameList = itemnames.Names.ToList();
var valueList = itemnames.Values.ToList();
for (int i = 0; i < itemnames.Names.Count(); i++)
{
if (valueList[i] != null && nameList[i] != null)
{
var name = nameList[i].ToString();
var value = valueList[i].ToString();
itemValues[itemnames.SystemName].Add(new KeyValuePair<string, string>(name, value));
}
}
}
}
public string Get(string itemSystemname, string fieldnames)
{
if (itemValues != null && itemValues[itemSystemname] != null && itemValues[itemSystemname].Any(f => f.Key == fieldnames))
{
return itemValues[itemSystemname].FirstOrDefault(f => f.Key == fieldnames).Value;
}
return string.Empty;
}
public List<string> GetAll(string itemSystemname)
{
return itemValues[itemSystemname].Where(item => item.Key == "Id").ToList();
}
}
如何实现此功能。在此先感谢
答案 0 :(得分:2)
更新后:itemValues来自类型:Dictionary<string, HashSet<KeyValuePair<string, string>>>
HashSet没有实现[]
运算符,因此您无法按照自己的方式执行此操作。你应该做的是:
itemValues["FrontPageNewsLarge"].Where(item => item.Key == "ID")
//For when you get the field from a parameter and what to output only the "value"
itemValues[itemSystemname].Where(f => f.Key == fieldNames).Select(f=> f.Value)
或者将itemValues
改为像bellow
假设itemValues
类似于Dictionary<string, Dictionary<string, int>> itemValues = new Dictionary<string, Dictionary<string, someObject>>
然后只是:
public Dictionary<string, someObject> GetAll(string itemSystemname)
{
return itemValues[itemSystemname];
}
foreach (var item in i.GetAll("FrontPageNewsLarge"))
{
item["ID"];
}
但是为什么要使用一个功能呢?只写:
foreach(var item in itemValues["FrontPageNewsLarge"])
{
var doSomethingWith = item["ID"];
}
(只需确保字典中确实存在“FrontPageNewsLarge”和“ID”)
如果您需要所有ID,您还可以做什么:
itemValues["FrontPageNewsLarge"].Select(item => item["ID"]);