LINQ

2016-03-24 19 views
0

aşağıdaki çok benzeyen bir sorgu var seti:LINQ

var query = plans 
.Where(p => 
     p.IsOptOut || 
     (p.PropertyType == PropertyType.Property1 && p.SomeCollection.Count > 0)) 
.Select(p => 
     new CustomClass 
     { 
      Id = p.Id, 
      PropertyType = p.PropertyType, 
      IsOptOut = p.IsOptOut 
     }); 

yüzden plans arasından seçim IsOptOut doğrudur VEYA p.PropertyType herhangi kayıtları özgüdür değeri VE p.SomeCollection en az bir kayda sahiptir.

Bu aşağıdaki gibi ayarlayın olası bir sonucu kendisine ödünç olacaktır: LINQ sorgusu değiştirebilir nasıl

Id   PropertyType   IsOptOut 
1   Foo     true 
2   Foo     false 
3   Foo     false 
4   Bar     true 
5   Baz     true 
6   Baz     false 

şekilde hüküm plans koleksiyonunda diğer kayıtlara geçerli kaydı karşılaştırabilirsiniz NEREDE ve IsOptOut'un gerçek olduğu tüm kayıtları hariç tutunuz VE verilen özellik tipi için döndürülen tek kayıt.

Yukarıdaki örnekte, ID # 4 sonuç kümesinden çıkarılmalıdır çünkü IsOptOut doğrudur ve "Bar" PropertyType için sonuç kümesinde başka hiçbir kayıt yoktur.

Bir yan not olarak, IsOptOut doğruysa, SomeCollection içinde kayıt olmayacaktır.

cevap

1

Aynı Where fıkrada doğrudan bunu yapamam, ama böyle bir şey kullanabilirsiniz (yorumlara bakınız):

var query = plans 
.Where(p => 
     p.IsOptOut || 
     (p.PropertyType == PropertyType.Property1 && p.SomeCollection.Count > 0)) 
.GroupBy(p => p.PropertyType) // group the result by property type so we can count the items 
.Where(g => !(g.Count() == 1 && g.FirstOrDefauilt().IsOptOut)) // apply the requested criteria 
.SelectMany(g => g) // flatten back the result 
.Select(p => 
     new CustomClass 
     { 
      Id = p.Id, 
      PropertyType = p.PropertyType, 
      IsOptOut = p.IsOptOut 
     }); 
+0

çalıştı, teşekkürler! – Scott