![](/img/trans.png)
[英]How can I return a single value integer from Linq from an array of objects that have other nested values
[英]How can I use linq to return integers in one array that do not match up with an integer property of another array?
我有以下方法簽名:
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();
}
如果您只需要返回ID,則可以使用以下內容:
existingStudents.Select(es => es.StudentID)
.Except(linkedStudents.Select(ls => ls.ServerID));
你可以用查詢理解形式寫這個,但我認為它不太清楚:
var result = (from es in existingStudents select es.StudentID);
.Except
(from ls in linkedStudents select ls.ServerID)
如果需要將結果作為數組返回,只需使用.ToArray()
擴展名:
existingStudents.Select(es => es.StudentID)
.Except(linkedStudents.Select(ls => ls.ServerID)).ToArray();
如果您只需要返回ID中的設置差異,則無需創建自己的相等比較器。
List<student> ExistingStudents = new List<student>();
List<student> LinkedStudents = new List<student>();
ExistingStudents.Add(new student {id=1, name="joe"});
ExistingStudents.Add(new student { id = 2, name = "beth" });
ExistingStudents.Add(new student { id = 3, name = "sam" });
LinkedStudents.Add(new student { id = 2, name = "beth" });
var students = from stud in ExistingStudents
where !(LinkedStudents.Select(x => x.id).Contains(stud.id))
select stud;
foreach(student s in students)
{
System.Diagnostics.Debug.WriteLine(string.Format("id: {0}, name: {1}", s.id, s.name));
}
簡單的學生班:
public class student
{
public int id;
public string name;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.