2015-10-20 56 views
0

我有兩個Users類的列表,即UsersExisting,UsersToUpdate。 類結構如下所示。LINQ來檢查一個列表<T>是否是另一個列表的子集<T>

public class Users 
{ 
    public string Name{get;set} 
    public Roles[] AvailableRoles{get;set} 
} 

class Roles 
{ 
    public int Serial{get;set} 
    public string Name{get;set} 
    public bool IsActive{get;set} 
} 

我必須檢查UsersToUpdate是否已經擁有UsersExisting的所有角色詳細信息。

例如,這是名單

UsersExisting.AvailableRoles={{1,"admin",true},{2,"hr",false},{3,"it",true}}; 
UsersToUpdate.AvailableRoles={{1,"admin",true},{2,"hr",false},{3,"it",true},{4,"finance",false}}; 

如何與LINQ做到這一點。

我這樣做。

bool isUsersUpdated = !UsersExisting.AvailableRoles 
.Except(UsersToUpdate.AvailableRoles).Any(); 

這是拋出錯誤。

+0

'users_true名單users'的子集 - 在我看來,周圍的其他方式,用戶是users_true的一個子集。 – Maarten

+5

檢查這個問題和答案:[鏈接](http://stackoverflow.com/q/332973/261050) – Maarten

+0

你正在使用什麼數據類型?什麼是「{1,admin,true}」?提供課堂描述並向我們展示您的嘗試。只有一些僞代碼。我們不能重現您的問題 –

回答

0

我認爲你正在尋找這裏的擴展方法是相交 - 在您的情況您正在尋找沒有結果回到表明它不會在超級列表中存在

if(!UsersToUpdate.AvailableRoles.Intersect(UsersExisting.AvailableRoles).Any()) 
{ 
     //your code here  
} 
0

由於您的名單Role對象的列表,你可能不希望使用Contains(或Except),因爲這隻會告訴你是否那些特定對象實例在列表 - 換句話說,它的對象比較引用,不是對象內容。 (除非,就是說,你改變了你的班級的「等於」意思,per @ poke的答案)。

不過,我想,一個角色的Serial屬性是一個唯一的標識符,您可以使用此目的 - 在這種情況下,你可以做這樣的事情:

bool isUsersUpdated = !UsersExisting.AvailableRoles.Select(r => r.Serial) 
         .Except(UsersToUpdate.AvailableRoles.Select(r => r.Serial)) 
         .Any(); 

(雖然我個人構建查詢不同)。

0

不幸的是,你的問題還不完整。你沒有說你到達那裏的錯誤。所以這裏有一個工作的例子。注意,Mrinal Kamboj提到的,你需要實現EqualsGetHashCode您的自定義類型,以便將它們過濾掉:

List<Roles> existing = new List<Roles> 
{ 
    new Roles(1, "admin", true), 
    new Roles(2, "hr", false), 
    new Roles(3, "it", true) 
}; 
List<Roles> available = new List<Roles> 
{ 
    new Roles(1, "admin", true), 
    new Roles(2, "hr", false), 
    new Roles(3, "it", true), 
    new Roles(4, "finance", false) 
}; 

bool isUsersUpdated = !existing.Except(available).Any(); 
Console.WriteLine(isUsersUpdated); 


// modified Roles class 
class Roles 
{ 
    public int Serial { get; set; } 
    public string Name { get; set; } 
    public bool IsActive { get; set; } 

    public Roles(int serial, string name, bool isActive) 
    { 
     Serial = serial; 
     Name = name; 
     IsActive = isActive; 
    } 

    public override bool Equals(object obj) 
    { 
     Roles other = obj as Roles; 
     if (other == null) 
      return false; 
     return Serial == other.Serial && Name == other.Name && IsActive == other.IsActive; 
    } 

    public override int GetHashCode() 
    { 
     return new { Serial, Name, IsActive }.GetHashCode(); 
    } 
} 
相關問題