簡體   English   中英

C# linq,獲取 object 屬性的不同值列表,並在 groupby 查詢中檢查 null

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

嘿,我有一個 object 被分組以獲得一些查詢。 對於其中一個 SchoolInfoType 屬性,我想獲取所有不同屬性 typeValues(SchoolInfoType 的屬性)的列表,其中 typeName(schoolInfoType 的屬性)= 字符串列表中的 recess,但我似乎無法讓它工作。 學校信息類型也可能是 null,所以我還需要對屬性進行 null 檢查。 我想要的最終返回類型是列表。

到目前為止,當我真的只想要 1 時,我所擁有的似乎是雙重可枚舉。

示例代碼


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();

學校結構 信息類型 Object 相關信息

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



內部 select 是導致嵌套 output 的原因

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

您的查詢要求TypeValueIEnumerable是不同的並且 == recess,從按空值過濾的IEnumerable中過濾。 這種嵌套是不清楚的,並且是最終結果是嵌套IEnumerable的原因。 您正在選擇 select

Select 將為您生成一個IEnumerable ,因此在另一個 select 中進行選擇將使您嵌套。 更不用說當它將 IL 降級為嵌套循環時,時間和空間的復雜性將會受到影響

暫無
暫無

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

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