簡體   English   中英

linq查詢常見關聯

[英]linq query for common associations

我要解決一個linq問題,我有一些用戶可以屬於多個組,現在我可以返回屬於單個組的用戶,如下所示:

    List<Student> students = new List<Student>();
    public List<Student> ReturnStudentByGroupName(string groupName)
    {
        List<Student> student = (from g in students
                              where
                                  (from t in g.StudentGroup where t.GroupName == groupName select t).Count() > 0
                              select g).ToList();
        return student;
    }

我現在的問題是我需要找到多個組的普通用戶嗎? 例如,誰是組A和組B的共同成員。我不在查找這兩個組的用戶列表,則僅他們屬於兩個組時才應返回用戶。

有誰知道如何使用兩個字符串作為輸入來執行此操作,即字符串firstgroupName,字符串secondgroupName。 然后返回普通學生?

IEnumerable<Student> StudentsOfGroup(Group g)
{
    return students.Where(s => s.StudentGroup.Contains(g));
}

IEnumerable<Student> CommonStudents(IEnumerable<Group> groups)
{
    return groups
        .Select(StudentsOfGroup)
        .Aggregate((acc, g) => acc.Intersect(g));
}

或根據組的數量,以下操作可能會更快:

IEnumberable<Student> CommonStudents(IEnumerable<Group> groups)
{
    var groupSet = new HashSet<Group>(groups);
    return students.Where(s => groupSet.IsSubsetOf(s.StudentGroup));
}
IEnumberable<Student> GroupIntersection(IEnumerable<Group> groups)
{
    return students
        .Where(s => groups.All(g => s.StudentGroup.Contains(g)));
}

好吧,您說您只想返回屬於A和B組的用戶的列表,因此自然地,您只需要使用兩個條件而不是一個條件來修改where語句。

    List<Student> students = new List<Student>();
    public List<Student> GetIntersectingStudents(string groupOne, string groupTwo)
    {
        var student = from s in students
                      let grps = s.StudentGroup.ConvertAll(gn => gn.GroupName)
                      where grps.Contains(groupOne) && grps.Contains(groupTwo)
                      select s;
        return student.ToList();
    }
    public List<Student> GetIntersectingStudents(params string[] groups)
    {
        var student = from s in students
                      let grps = s.StudentGroup.ConvertAll(gn => gn.GroupName)
                      where !groups.Except(grps).Any()
                      select s;
        return student.ToList();
    }

這是為您提供的幾種方法,其中一種在方法中使用兩個參數(您要的內容),而另一種則使用組列表(如果您需要從三個中獲取而不是兩個,等等)。

編輯:

我以為我也會把這種額外的方法扔在那里,只是為了好玩。 它編譯所有組及其成員的列表。

    public static Dictionary<string, List<Student>> GetStudentGroups()
    {
        var temp = from s in students
                   let grps = s.StudentGroup.ConvertAll(gn => gn.GroupName)
                   from grp in grps
                   group s by grp
                   into g
                   select g;
        return temp.ToDictionary(grping => grping.Key, studnt => studnt.ToList());
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM