2017-04-13 72 views
0

我已經在XLAMIN的PCL中實現了領域。這工作正常,並且應該(數據正在存儲和檢索)。Realm C# - 空集合的LINQ

現在我正在構建越來越多的功能,我遇到了無法找到查詢空集合的情況。

由於模型綁定的原因,我需要返回IRealmCollection<Customer>,所以我無法枚舉,然後篩選出沒有結實的項目。

任何想法如何使這種情況發生在IQueryable?

我試圖

var realm = Realm.GetInstance(); 
var customers = realm.All<Customer>(); 
// errors out - only Realm-managed props can be used 
customers = customers.Where(x => x.BlogEntries.Count > 0)); 
// errors out - Any() is not supported 
customers = customers.Where(x => x.BlogEntries.Any()); 
// errors out - Datatype mismatch in comparison 
customers = customers.Where(x => x.BlogEntries != null); 
// errors out - Datatype mismatch in comparison 
customers = customers.Where(x => x.BlogEntries == default(IList<BlogEntries>)); 
+0

爲什麼甚至試圖查詢一個空的集合?如果它是空的,它將永遠不會給出結果。相反,如果集合是空的,則限定它,如果是,則忽略它。想想像一個盒子的集合。你是否試圖從盒子裏拿出一件物品,或者先檢查它是否有任何東西? – Takarii

+0

@Takarii我只需要有博客的客戶。這是一個特定於領域的問題,需要與常規.NET問題不同的答案。 –

+0

您是否嘗試過使用'realm.All ().Where(x => x.BlogEntries.Count> 0).ToList(); '? (我認爲額外的右括號是一個錯字) – Takarii

回答

0

遺憾的是不支持的境界Xamarin 1.2.0。你可以做的是實現一個人可憐的最愛的通知來解決這個問題:

public class MyViewModel 
{ 
    private IRealmCollection<BlogEntry> _blogEntries; 
    private IEnumerable<Customer> _customers; 

    public IEnumerable<Customer> Customers 
    { 
     get { return _customers; } 
     set { Set(ref _customers, value); } 
    } 

    public MyViewModel 
    { 
     Customers = realm.All<Customer>() 
         .AsEnumerable() 
         .Where(c => !c.BlogEntries.Any()) 
         .ToArray(); 

     _blogEntries = realm.All<BlogEntry>().AsRealmCollection(); 
     _blogEntries.CollectionChanged += (s, e) => 
     { 
      var updatedCustomers = realm.All<Customer>() 
             .AsEnumerable() 
             .Where(c => !c.BlogEntries.Any()) 
             .ToArray(); 

      if (!IsEquivalent(updatedCustomers, Customers)) 
      { 
       Customers = updatedCustomers; 
      } 
     }; 
    } 

    private bool IsEquivalent(Customer[] a, Customer[] b) 
    { 
     if (a.Length != b.Length) 
     { 
      return false; 
     } 

     for (var i = 0; i < a.Length; i++) 
     { 
      if (!a[i].Equals(b[i])) 
      { 
       return false; 
      } 
     } 

     return true; 
    } 
} 

當我們調用ToArray()我們只輸集合更改通知,我們通過觀察博客天真地落實這些領域條目的收集和如果更新了任何內容,請做一個簡單的檢查。如果你覺得這樣,你可以擴展這個解決方案並將其包裝在INotifyCollectionChanged的自定義實現中並綁定到該解決方案。然後,您甚至可以應用一些語義來提出正確的集合更改事件(或者爲每個更改選擇一個簡單的.Reset)。

爲了解決任何性能問題,在Realm集合上調用ToArray不會實現對象的屬性,因此它相對便宜。唯一稍微昂貴的操作是遍歷所有Customer對象並檢查它們的BlogEntries列表。我的建議是嘗試一下,看看它是否滿足您的使用情況。