简体   繁体   English

使用lambda聚合匿名类型

[英]Aggregating anonymous types using lambda

I'm trying to print out a list of phone numbers (\\n for each number) in a format {type}:{number}. 我正在尝试以{type}:{number}的格式打印出电话号码列表(每个数字\\ n)。 So from a list of 2 numbers I would print out: 因此,从2个数字的列表中,我会打印出:

 Home: 111-111-1111
 Cell: 222-222-2222

So far I can select into an anonymous type but when I go to aggregate it is leterally printing out the whole anonymous type on the screen looking exactly like below: 到目前为止,我可以选择一种匿名类型,但是当我进行汇总时,可以在屏幕上完全打印出整个匿名类型,如下所示:

 new { phoneType = Home + ": ", phoneNumber = 111-111-1111 }

Should I even be using aggregate? 我什至应该使用聚合吗? This is what I'm working with: 这就是我正在使用的:

  PhoneNumbers.Select(x => new { phoneType = x.PhoneType, phoneNumber = x.PhoneNumber1 }).Aggregate(
                (p, x) => new { phoneType = p.phoneType + ": ", x.phoneNumber });

If you just want the phone numbers as strings, you can create that string in a Select call: 如果仅要将电话号码作为字符串,则可以在“ Select呼叫中创建该字符串:

var x = PhoneNumbers.Select(x => string.Format("{0}: {1}", x.PhoneType, x.PhoneNumber));

Your Aggregate call is basically a bug (assuming it even compiles) because you're combining the "current" phone number with the previous phone type. 您的“汇总”通话基本上是一个错误(假设甚至可以编译),因为您将“当前”电话号码与以前的电话类型结合在一起。 It's also unnecessary for combining the phone numbers as text because of existing string methods: 由于现有的字符串方法,也不需要将电话号码组合为文本:

var phoneNumberStrings = PhoneNumbers.Select(x => string.Format("{0}: {1}", x.PhoneType, x.PhoneNumber));
var text = string.Join(Environment.NewLine, phoneNumberStrings);

While you could do this with IEnumerable<string>.Aggregate , I feel it's cleaner if you just use string.Join . 虽然您可以使用IEnumerable<string>.Aggregate做到这IEnumerable<string>.Aggregate ,但我觉得如果只使用string.Join ,它会更干净。 Someone reading your code will be able to more easily get the meaning out if they see "join these strings with newline." 如果有人看到“用换行符连接这些字符串”,那么阅读您的代码的人将可以更轻松地理解其含义。

string.Join(
    Environment.NewLine,
    PhoneNumbers.Select(x =>
        string.Format("{0}: {1}", x.PhoneType, x.PhoneNumber));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM