C# Linq问题

标签 c# linq dictionary

我拼命地试图理解 linq,现在我有了一个具体的例子来说明我想做什么(但失败了):

Console.WriteLine("{0}", (from myaddresses[x].PostalNr where x => myaddresses[x].SortType == "110" ))

myaddressOneAddress 对象(我自己的对象)的字典,该对象包含属性 SortTypePostalNr.

我认为我不需要循环来执行上述操作,但是当重写上述内容时,它可能只需要它获得的第一个命中,或者?

我要执行的题目是:
对于字典中将 SortType 设置为 110 的每个条目,打印出它的邮政编码。

最佳答案

下面是一种方法的分步演练。

要设置示例数据(根据您的问题),我们有 OneAddress类:

class OneAddress
{
    public string PostalNr { get; set; }
    public string SortType { get; set; }
}

这是在 Dictionary 中所以我们有:

var myAddresses = new Dictionary<int, OneAddress>();
myAddresses.Add(1, new OneAddress() { PostalNr = "123", SortType = "101" });
myAddresses.Add(2, new OneAddress() { PostalNr = "124", SortType = "110" });
myAddresses.Add(3, new OneAddress() { PostalNr = "125", SortType = "101" });
myAddresses.Add(4, new OneAddress() { PostalNr = "126", SortType = "110" });
myAddresses.Add(5, new OneAddress() { PostalNr = "127", SortType = "110" });

首先,获取所有字典条目的基本 Linq 查询:

var results = from a in myAddresses
            select a;

这将返回一个 IEnumerable<T>其中 TKeyValuePair<int, OneAddress> (与我们的词典相同)。

如前所述,您只需要 PostalNr不是 KeyValuePair所以我们将查询更改为:

var results = from a in myAddresses
            select a.Value.PostalNr;

Value包含 OneAddress对象,我们只得到我们需要的属性(在 IEnumerable<T> 中)。

但这适用于集合中的所有项目;我们现在可以添加过滤器了。

var results = from a in myAddresses
             where a.Value.SortType == "110"
            select a.Value.PostalNr;

现在我们得到了 PostalNr对于任何 OneAddress在词典中 SortType"110" ,这只会将结果打印到控制台屏幕。

正如其他答案中强调的那样,Console.WriteLine()不适用于可枚举的字符串列表,因此我们可以枚举项目:

foreach (string postalNr in results)
{
    Console.WriteLine(postalNr);
}

或者(如果我们使用 System.Collections.Generic)我们可以在一行中完成:

results.ToList().ForEach(p => Console.WriteLine(p));

关于C# Linq问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25807539/

相关文章:

c# - WPF 服务器应用程序

c# - 使用 LINQ 查找某个函数上的哪个元素 "scores highest"

python - 您如何为用户定义的对象定义类似字典的赋值?

list - unix - 如何从字典列表中的每个字典中获取 (2) 列

Python:在列表字典中使用 Counter

c# - 转换字符(又名 : '+' ) to an operator

c# - Visual Studio 2017 中的 Windows Forms Application menuStrip 比 2019 更方便?

c# - 如何删除语音事件处理程序?

c# - 如何将指定属性的 lambda 表达式转换为表示相同属性的 asp.net mvc 兼容 'name' 字符串?

c# - 日期之间的 Linq 复杂查询搜索