1

I am not really sure why this is not working correctly. Is it possibly because I am trying to use the expressions on a data class instead of a single field in that class?

adminOnlyGroups is supposed to return the groups that the admin has and the user doesn't but it is returning all of the admin groups

userOnlyGroups is doing the same, it is returning all of the user groups

commonGroups is supposed to return the groups that they have in common which there are two of, but it is returning null or empty

Data Class

[DataContract]
public class InvestigatorGroupData
{

    [DataMember]
    public int InvestigatorGroupId { get; set; }

    [DataMember]
    public string InvestigatorGroupName { get; set; }

}

Snippet of my controller

IEnumerable<InvestigatorGroupData> adminGroups = proxy.GetInvestigatorGroups(adminId);
IEnumerable<InvestigatorGroupData> userGroups = proxy.GetInvestigatorGroups(userId);

// Groups that admin has and user doesn't. These will be enabled and unselected
IEnumerable<InvestigatorGroupData> adminOnlyGroups = adminGroups.Except(userGroups);

// Groups that the user has and admin doesn't. These will be disabled and selected
IEnumerable<InvestigatorGroupData> userOnlyGroups = userGroups.Except(adminGroups);

// Groups in common. These will be enabled and selected
IEnumerable<InvestigatorGroupData> commonGroups = adminGroups.Intersect(userGroups);

if (commonGroups.IsNullOrEmpty())
{
    return View("Error");
}
Eitan K
  • 837
  • 1
  • 17
  • 39

1 Answers1

0

You need to implement an equality comparer for objects

This has been answered before here Using Linq Except not Working as I Thought

Please see the blog post below from MSDN for further explanation http://blogs.msdn.com/b/csharpfaq/archive/2009/03/25/how-to-use-linq-methods-to-compare-objects-of-custom-types.aspx

If you are anonymous types it will work differently without an equality comparer. Here is an example code

http://odetocode.com/blogs/scott/archive/2008/03/25/and-equality-for-all-anonymous-types.aspx

Community
  • 1
  • 1
samsur
  • 286
  • 1
  • 11
  • 1
    If you find a duplicate question you should be *voting to close the question as a duplicate* not posting a link to the duplicate in an answer. – Servy Oct 22 '15 at 15:21
  • Thanks Servy. I wasn't planning to score points for posting duplicate links. Just trying to be helpful here. I will however give you a vote for suggesting this. Thanks – samsur Oct 22 '15 at 15:27
  • The blog worked perfectly, thanks a lot! – Eitan K Oct 22 '15 at 17:12