【问题标题】:error when anonymous type is used in join query in LINQ在 LINQ 的连接查询中使用匿名类型时出错
【发布时间】:2011-06-23 15:18:23
【问题描述】:

这些天我开始学习 LINQ。当我尝试在连接查询中返回匿名类型时出现错误。而且我不明白为什么会出现此错误。 这是我的编码。

List<Student> students = new List<Student>()
        {
            new Student{First="Svetlana",Last="Omelchenko",ID=111,Scores= new List<int>(){97,92,81,60}},
            new Student{First="Claire",Last="O'Donnell",ID =112,Scores=new List<int>(){75,84,91,39}},
            new Student{First ="Sven",Last="Mortensen",ID =113,Scores=new List<int>(){88,94,65,91}},
            new Student{First ="Cesar",Last="Garcia",ID=114,Scores=new List<int>(){97,89,85,82}}
        };

    List<ContactInfo> contactList = new List<ContactInfo>()
    {
        new ContactInfo{ID=111,Email="Contoso",Phone= "206-555-0108"},
        new ContactInfo{ID=112,Email="ClaireO@Contoso.com",Phone="206-555-0298"},
        new ContactInfo{ID=113,Email="SvenMort@Contoso.com",Phone="206-555-1130"},
        new ContactInfo{ID=114,Email="CesarGar@Contoso.com",Phone="206-555-0521"}
    };

var cInfo =
            from student in students
            where student.Scores.Average() > 85
            join ci in contactList on student.ID equals ci.ID
            select new { ci.Email, student.First };
        foreach (var c in cInfo)
            Console.WriteLine("{0)'s email is {1}", c.First, c.Email);

在匿名类型中,我收到来自contactList 的电子邮件和学生的名字。我不能这样做???

提前致谢。

凯文

【问题讨论】:

  • @Vincent >> 谢谢你的提问。对不起。错误来自另一行,而不是来自 linq !错误已解决。很抱歉打扰您。

标签: linq anonymous-types query-expressions


【解决方案1】:

您的字符串格式表达式中有一个括号而不是大括号。

"{0)'s email is {1}"

应该是

"{0}'s email is {1}"

。当我进行此更改时,输出为:

Cesar 的电子邮件是 CesarGar@Contoso.com

【讨论】:

  • 哦,太不公平了。比你早 1 分钟,你也会得到我的 +1 :) +1。
  • @Phill True,但我比你更需要代表! :D 我也为你 +1。
  • 我知道,我只是觉得这很有趣 :) 你的回答比我的解释得更好,所以你比我更值得接受。
【解决方案2】:

我将假设您收到错误“输入字符串的格式不正确”

Console.WriteLine("{0)'s email is {1}", c.First, c.Email);

^ 你的第一个参数有 ) 不是 }

【讨论】:

  • 我也给了 u + 1。对不起,我碰巧首先看到了文森特的评论!再次感谢!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-23
  • 2021-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多