简体   繁体   中英

C# linq, get a list of distinct values of a object property, with null check in a groupby query

Hey I have a object being grouped to get a number of queries. For one of the properties SchoolInfoType I want to get list of all the distinct properties typeValues (property of SchoolInfoType) where typeName (property of schoolInfoType) = recess in a string list, but I can't seem to get it to work. School Info type may also be null so I also need to do a null check on properties. Final return type I want is List.

What I have so far, seems to be making a double enumerable, when I really only want 1.

Example code


var data = session.GroupBy(x => x.SchoolId).Select( a => new SchoolObject { 
StudentHours = a.Sum(m => m.Hours),

// Query I tried but doesnt return correct return type end up getting embedded enumerables
// need the null check to prevent exception on comparing on null type, end result should 
be list of unique type values matching where conditions
Types = a.Where( x => x.SchoolInfoType != null)
.Select( t => t.SchoolInfoType.Where(d => d.typeName == "recess")
.Select(n => n.TypeValue).Distinct))

}).ToList();

Structure of School Info Type Object relevant info

public class SchoolInfoType {
public string TypeName {get; set; }
public string TypeValue {get; set; }
}



The internal select is what is causing the nested output

Types = a.Where(x => x.SchoolInfoType != null)
         .Select(x => x.SchoolInfoType)
         .Where(x => x.typeName == "recess")
         .Select(n => n.TypeValue)
         .Distinct()
         .ToList();

Your query is asking for IEnumerable of TypeValue 's that is distinct and == recess, filtered from an IEnumerable that was filtered on nulls. This sort of nesting is unclear and is the cause of the end result being a nested IEnumerable . You are selecting within a select

A Select is going to produce you an IEnumerable , so selecting within another select is going to get you nesting. Not to mention the time and space complexity is going to suffer when it steps down the IL to nested loops

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM