我正在编写以下代码,以根据用户将指定的搜索短语查找“描述”。将键视为重要的短语,将值视为对去哪里找到该短语的描述。
例如,将其视为商店定位器(我能想到的最佳类比)。如果您搜索“目标”(键),您将获得大量城市(值),其中一些可能具有相同的名称。所以同一个城市可以有多个Target。
Dictionary
显然行不通,因为我要么有重复的商店名称,要么可能有重复的城市名称。这让我想到了我的实际情况:
基本上,我从 List<KeyValuePair<string, string>>
开始允许双向重复,然后将其转换为 Lookup<string, string>
我认为这不会像结果那样令人困惑。
List<KeyValuePair<string, string>> kvpList = new List<KeyValuePair<string, string>>();
Lookup<string, string> collection;
kvpList.Add(new KeyValuePair<string, string>("K1", "R1"));
kvpList.Add(new KeyValuePair<string, string>("K1", "R1"));
kvpList.Add(new KeyValuePair<string, string>("K1", "R2"));
kvpList.Add(new KeyValuePair<string, string>("K2", "R1"));
kvpList.Add(new KeyValuePair<string, string>("K2", "R2"));
kvpList.Add(new KeyValuePair<string, string>("K2", "R3"));
kvpList.Add(new KeyValuePair<string, string>("K2", "R1"));
collection = (Lookup<string,string>)kvpList.ToLookup(k => k.Key, k => k.Value);
以上只是虚假的测试信息,但我觉得必须有一种更干净的方法来从 Lookup
中获取结果特别是因为它看起来对 Linq 非常友好。不幸的是,我对 Linq 很不熟悉,而且 Linq 本身的语法似乎不太适合初学者。我在这段代码中得到了结果(硬编码的搜索词只是为了测试目的):
string searchTerm = "K2";
List<string> uniqueResults = new List<string>();
foreach (var item in collection)
{
if (item.Key.Contains(searchTerm))
{
foreach (var value in item)
{
if (!uniqueResults.Contains(value))
{
uniqueResults.Add(value);
Console.WriteLine("Added: " + value);
}
else
{
Console.WriteLine("Skipped duplicate: " + value);
}
}
}
}
我对上面的代码没有任何问题,但我的问题是:有没有办法使用 Linq 来实现我想要实现的目标?我觉得我所拥有的并不是最好的方法...
可能值得注意的是部分 searchTerm
还必须能够找到它出现在键中的结果(因此包含)。现有答案不能完全回答我的具体问题。我找不到可以帮助我通过部分键搜索获取值的工具。
最佳答案
翻译成 LINQ 的代码如下所示:
var uniqueResults = collection
.Where(item => item.Key.Contains(searchTerm)) // filter the collection
.SelectMany(x => x) // flatten results
.Distinct() // remove duplicates
.ToList();
您甚至不需要Lookup
。您可以使用 kvpList
获得相同的结果:
var uniqueResults = kvpList
.Where(item => item.Key.Contains(searchTerm)) // filter the collection
.Select(item => item.Value) // get the Values from KeyValuePairs
.Distinct() // remove duplicates
.ToList();
LINQ 解决方案实际上比命令式解决方案更容易理解。尝试用英语描述您的算法:从 kvpList
中,选择不同的值,其中键包含搜索词。这几乎就是第二个 LINQ 代码。
关于c# - Linq 替代键(或部分键)检索查找值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33350793/