为什么这个 LINQ 查询会抛出 InvalidCastException

本文关键字:InvalidCastException 查询 LINQ 为什么 | 更新日期: 2023-09-27 18:34:28

我在这一行收到一个InvalidCastException:

List<Student> studentsWithSameSurname =
    (List<Student>)_studentsList
        .Where(i => i.LastName == textBoxLastName.Text.Trim())
        .GroupBy(j => j.FamilyID);

_studentsList是一个List<Student>,所以我不知道为什么(List<Student>(是一个无效的演员表。

对于那些需要更多上下文的用户,这是一个 Winforms 应用程序,其中我将自定义类的泛型列表序列化为 json 文件,然后在我想处理数据时使用反序列化它,并使用 LINQ 查询它。

_studentsList是这样定义的:

List<Student> _studentsList;

学生类是:

public class Student
{
    public int StudentID { get; set; }
    public int FamilyID { get; set; }
    public bool EnrolledInAYttFM { get; set; }
    public DateTime DateEnrolledOrHiatusAYttFM { get; set; }
    public bool GivesBibleReading { get; set; }
    public bool PresentsICRVBS { get; set; }
    public bool IsHouseholder { get; set; }
    public bool IsMale { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string EmailAddr { get; set; }
    public DateTime WeekOfLastAssignment { get; set; }
    public int RecommendedNextTalkTypeID { get; set; }
    public int NextCounselPoint { get; set; }
}

我试图做的背后的逻辑是:

如果添加了学生,并且他们的姓氏已存在于通用列表中,则需要确定该姓名的第二个实例是否与前一个家庭属于同一家庭。更具体地说,如果添加"史密斯",并且他们是第一个拥有该姓氏的人,他们将获得下一个可用的 familyID;否则(如果已经输入了该姓氏(,则必须确定他们是否属于已经输入的家庭之一,或者他们是否是新家庭的第一个成员:

Student surNameCandidateRecord = _studentsList.SingleOrDefault(s => s.LastName == textBoxLastName.Text);
if (null == surNameCandidateRecord)
{
    student.FamilyID = _studentsList.Max(x => x.FamilyID) + 1;
}
else // at least one family with that surname exists already
{
    student.FamilyID = GetFamilyID();
}

GetFamilyID(( 方法是抛出此异常的方法,这里是完整的:

private int GetFamilyID()
{
    List<KeyValuePair<int, string>> familyIDsAndNames;
    // InvalidCastException on the line below
    List<Student> studentsWithSameSurname = (List<Student>)_studentsList.Where(i => i.LastName == textBoxLastName.Text.Trim()).GroupBy(j => j.FamilyID);
    // </ InvalidCastException on the line above
    familyIDsAndNames = new List<KeyValuePair<int, string>>();
    foreach (Student s in studentsWithSameSurname)
    {
        string fullNameWithFamilyIdPrepended = String.Format("({0}). {1} {2}", s.FamilyID, s.FirstName, s.LastName);
        familyIDsAndNames.Add(new KeyValuePair<int, string>(s.FamilyID, fullNameWithFamilyIdPrepended));
    }
    ChooseFamilyForm cff = new ChooseFamilyForm(familyIDsAndNames);
    cff.ShowDialog();
    return AYttFMConstsAndUtils.familyIDSelected;
}

在抛出 InvalidCastException 时,通用列表的内容是(名称和电子邮件地址已更改以保护垃圾邮件(:

[{"StudentID":1,"FamilyID":1,"EnrolledInAYttFM":true,"DateEnrolledOrHiatusAYttFM":"2016-02-12T21:52:55.9560088-08:00","GivesBibleReading":false,"PresentsICRVBS":true,"IsHouseholder":true,"IsMale":false,"FirstName":"Carly","LastName":"Shannon","EmailAddr":"carlyjeannette@att.net","WeekOfLastAssignment":"2015-08-12T21:52:50.6959113-07:00","RecommendedNextTalkTypeID":3,"NextCounselPoint":16},{"StudentID":2,"FamilyID":2,"EnrolledInAYttFM":true,"DateEnrolledOrHiatusAYttFM":"0001-01-01T00:00:00","GivesBibleReading":false,"PresentsICRVBS":true,"IsHouseholder":true,"IsMale":false,"FirstName":"Jennifer","LastName":"Volando","EmailAddr":"jenni_v@ymail.com","WeekOfLastAssignment":"0001-01-01T00:00:00","RecommendedNextTalkTypeID":0,"NextCounselPoint":0}]

。我正在尝试添加姓氏"Volando"的第二个人(因此将代码路由到 GetFamilyID(( 方法(。

我的 LINQ 查询可能是错误的,但我不知道以哪种方式。

更新

这是我成功使用的,基于托德克的回答:

List<Student> studentsWithSameSurname = (List<Student>)_studentsList
        .Where(i => i.LastName == textBoxLastName.Text.Trim())
        .OrderBy(j => j.FamilyID)
        .ToList();

我会尽快悬赏给迪乔答案;自从达到10K以来,我将做一个卡内基并"放弃"所有分数。

为什么这个 LINQ 查询会抛出 InvalidCastException

在这一行中

List<Student> studentsWithSameSurname =
    (List<Student>)_studentsList
        .Where(i => i.LastName == textBoxLastName.Text.Trim())
        .GroupBy(j => j.FamilyID);

你不是在投_studentsList;你是在投射整个表达式。换句话说,这相当于

    (List<Student>)(_studentsList
        .Where(i => i.LastName == textBoxLastName.Text.Trim())
        .GroupBy(j => j.FamilyID));

而不是(如您所料(

    ((List<Student>)_studentsList)
        .Where(i => i.LastName == textBoxLastName.Text.Trim())
        .GroupBy(j => j.FamilyID);

如果要获取作为 Linq 查询结果的列表,则必须使用 .ToList(( 方法:

     studentsList
        .Where(i => i.LastName == textBoxLastName.Text.Trim())
        .GroupBy(j => j.FamilyID)
        .ToList();

但是,您的结果不是List<Student>而是新类型,因为 GroupBy 方法会创建新的学生列表类型。IEnumerable<IGrouping<T, U>> 类型的GroupBy表达式 os 的结果,其中 T 是分组变量,U 是元素的类型;在您的情况下,如果FamilyIDint 类型,它将是 IEnumerable<IGrouping<int, Student>>

相关文章:
  • 没有找到相关文章