加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何使用linq在一个数组中返回与另一个数组的整数属性不匹

发布时间:2020-12-15 04:32:36 所属栏目:百科 来源:网络整理
导读:我有以下方法签名: internal static int[] GetStudentIDsThatAreNotLinked(PrimaryKeyDataV1[] existingStudents,IQueryableStudent linkedStudents) PrimaryKeyData是一个具有ServerID和LocalID整数作为属性的类. Student是一个类(在其他属性中)有一个名为
我有以下方法签名:
internal static int[] GetStudentIDsThatAreNotLinked(PrimaryKeyDataV1[]
       existingStudents,IQueryable<Student> linkedStudents)

PrimaryKeyData是一个具有ServerID和LocalID整数作为属性的类.
Student是一个类(在其他属性中)有一个名为StudentID的整数.

在英语中,我想要做的是返回一个整数数组,这些整数位于existingStudents […].ServerID但不在linkedStudents […]中.– StudentID

如果’existingStudents’和’linkedStudents’都是整数数组,我会使用如下的linq查询:

return from es in existingStudents where
    !linkedStudents.Contains<int>(es) select es;

..然后可以转换为一个整数数组.

我想要做的是给包含一个IEqualityOperator,如果PrimaryKeyData.ServerID == Student.StudentID,它将认为PrimaryKeyData类等于Student类

所以我认为我需要一个lambda表达式,但我对如何构造它非常困惑.

我想我正朝着正确的方向前进,但任何人都可以在最后的障碍中帮助我吗?

解决方法

所以,我的理解是你想获得PrimaryKeyDataV1的所有实例,其中ServerID属性不存在于linkedStudents参数的任何student.StudentID属性中?
internal static PrimaryKeyDataV1[] GetStudentsThatAreNotLinked(PrimaryKeyDataV1[] existingStudents,IQueryable<Student> linkedStudents)
{
    var results = existingStudents.Select(s => s.ServerID)
        .Except(linkedStudents.Select(link => link.StudentID))
        .ToArray();

    return existingStudents.Where(stud => results.Contains(stud.ServerID));
}

或者,如果您只想要一系列ID …

internal static int[] GetStudentIDsThatAreNotLinked(PrimaryKeyDataV1[] existingStudents,IQueryable<Student> linkedStudents)
{
    return existingStudents.Select(s => s.ServerID)
        .Except(linkedStudents.Select(link => link.StudentID))
        .ToArray();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读