Fuz*_*ans 5 c# linq lookup list
我正在查询xml文件并为每个选择返回3个属性(符合我的条件的每个条目将返回3个属性详细信息).我需要存储这些值,然后查找第一个属性,并返回与其相关的其他2个存储属性.
var items = from item in doc.Descendants("SUM")
select new
{
id = (string)item.Attribute("id"),
category = (string)item.Attribute("cat"),
selection = (string)item.Attribute("sel")
};
Run Code Online (Sandbox Code Playgroud)
上面的代码返回每个项目找到的3个属性.我需要存储这3个条目,以便它们关联在一起,然后再对存储的条目执行查找.例如,我需要能够查找id = 1的存储值,并返回相应的类别和选择条目.
我正在研究C#的Lookup方法,但不了解如何使用它.列表似乎可能有效,但我不知道如何将多个数据存储到列表中的条目中(可能连接成一个条目,但后来我不确定是否对它执行查找).任何关于如何使用LIST或LOOKUP(或其他未提及的方式)执行此操作的建议均值得赞赏.
您可以使用Where(或其他选项,例如FirstOrDefault等)进一步过滤:
var items = from item in doc.Descendants("SUM")
select new
{
Id = (string)item.Attribute("id"),
Category = (string)item.Attribute("cat"),
Selection = (string)item.Attribute("sel")
};
var filtered = items.Where(i => i.Id == 1);
// Then use these as needed
foreach(var item in filtered)
{
Console.WriteLine("Cat: {0}, Sel: {1}", item.Category, item.Selection);
}
Run Code Online (Sandbox Code Playgroud)
该ToLookup方法实际上有一个非常不同的目的。它构建了一个实现 的数据结构ILookup<T,U>,这是一个查找表,您可以在其中轻松返回与特定键匹配的所有项目。如果您要从数据中执行多次查找,这很有用,但如果您只想“查找”与单个值匹配的项目,则这不是很有用。