让我们先看看下面的结构(我试图简化它,只显示我想要的查询类型)
class NameAddress
{
public string Name { get; set; }
public string Address { get; set; }
public NameAddress(string sName, string sAddress) { Name = sName; Address = sAddress; }
}
static void Main(string[] args)
{
Dictionary<int, Dictionary<string, NameAddress>> _dictionary = new Dictionary<int,Dictionary<string,NameAddress>>()
{
{/*int Key=*/1, /*Dictionary<str, NameAddress> value(1)=*/new Dictionary<string, NameAddress>() { {"First", new NameAddress("John Doe", "Mexico")}} },
{/*int Key=*/2, /*Dictionary<str, NameAddress> value(2)=*/new Dictionary<string, NameAddress>() { {"Second", new NameAddress("Morris", "Washington")}, { "Third", new NameAddress("Keith", "New York")}} }
};
}
我想使用单个linq查询查询以下数据结构。 假设我想找到住在纽约和HIS钥匙的人。整数键(_dictionary键)并不重要,但字符串Key(在本例中为“Third”)是我想要找到的。
是否可以在单个linq查询中找到字符串Key和特定NameAddress?如果是,那该查询是什么?
答案 0 :(得分:1)
这不是支持此操作的有效数据结构。如果这是一项常见操作,您应该考虑采用新设计。
检查培养要求。
string address = "New York";
KeyValuePair<string, NameAddress> result =
_dictionary.Values
.SelectMany(value => value)
.FirstOrDefault(pair => pair.Value.Address.Equals(address, StringComparison.CurrentCultureIgnoreCase));
答案 1 :(得分:1)
请注意,对字典进行迭代(而不是使用索引),但它有效:
var found = (from outer in _dictionary
from inner in outer.Value
where inner.Value.Address == "New York"
select new {
OuterKey = outer.Key,
InnerKey = inner.Key,
NameAddress = inner.Value
}).FirstOrDefault();