2012-07-27 32 views
2

我收集了一些HierarchyNodeEntity值和集合祖先。 現在我想通過使用值db.HierarchyNodeEntitiestheAncestors得到值。如何使用包含在LINQ中使用C#

這裏我使用包含來實現這一點。但它不工作。我想用這個包含作爲運算符在SQL中。任何人都可以告訴我如何在此LINQ中使用Like。

在此先感謝。

這裏是代碼:

var q = from p in db.HierarchyNodeEntities       
         where theAncestors.Contains(p.HierarchyNodeEntity) 
         group p by p.PropertyKey 
         into prop 
         select 
          prop.OrderByDescending(p => p.LevelId). 
          FirstOrDefault(); 


    var list = q.ToList(); 
+1

你可以定義「它不工作」?你會得到一個異常或意外的結果等? – nemesv 2012-07-27 11:32:05

+0

我在我的集​​閤中獲得「0」值,但是包含HierarchyNodeEntity的集合。 – SuryaKavitha 2012-07-27 11:36:10

回答

2

SuryaKavitha,

它可能會或可能不會通過在物體通過比較作爲SQL不會明白哪些領域你指的是工作。您可能必須嘗試一些像:

[編輯]

theAncestors 
    .Where(x => x.myproperty.Contains(p.HierarchyNodeEntity.anotherproperty)) 

這是我最初的建議(也可以代替爲ContainsStartsWithEndsWith)。 Yopu甚至可以用直平等檢查工作,即:

theAncestors 
    .Where(x => x.myproperty == p.HierarchyNodeEntity.anotherproperty) 
+0

theAncestors是一個列表。所以我無法直接獲得myproperty,這意味着我無法檢查每個祖先的項目,因爲它的列表。你能告訴我怎樣才能從列表中找到一個單獨的項目在哪裏條件 – SuryaKavitha 2012-07-27 11:39:05

+0

gotcha,好吧,在這種情況下看到我的最新編輯 – 2012-07-27 11:40:08

+0

oops -2nd編輯,忘記刪除'theAncestors.myproperty'部分:-) – 2012-07-27 11:50:00

0

如果我得到了你的權利,你要like '%abc%' SQL符號。 您需要首先將您的值轉換爲string類型,然後才能使用contains。因爲IEnumberable.Contains不同。

theAncestors.Count(x => x.ToString().Contains(p.ToString())) > 0 
+0

但是祖先類型是List只有它的不是IEnumurable集合 – SuryaKavitha 2012-07-27 11:47:55

+0

@SuryaKavitha IEnumerable extends List ,添加擴展方法..('using System.Linq;') – flindeberg 2012-07-27 12:00:02