How to make "Not Equal " using Linq

Mohammad Qasim 576 Reputation points
2021-04-15T11:09:04.087+00:00

Hi,
using Sharepoint 2016 On Prem

I have created Linq query to extract data from 2 lists,

Suppose have 2 lists :
List A and , List B

Solution Required: want to retrive those data from list A ,which is not present on list B.

attached is the code image
88272-querymapwf.png
thanks

Microsoft 365 and Office SharePoint Server Development
0 comments No comments
{count} vote

Accepted answer
  1. ZhengyuGuo 10,586 Reputation points Moderator
    2021-04-16T07:10:23.92+00:00

    Hi @Mohammad Qasim ,

    If want to filter out resultUser "m_userid" not equal to resultwfUser "m_wfID", modify to this:

    var ListC = resultUser.Select(u=>u.m_userid).Except(resultwfuser.Select(x => x.m_wfID));  
    

    But the above will only return m_userid as using Select.

    Another better way will like this:

    var ListD = resultUser.Where(a => !resultwfuser.Select(b => b.m_wfID).Contains(a.m_userid));  
    

    This will return the who field which meets condition.

    Reference:

    Is there a “not equal” in a linq join

    Thanks
    Best Regards


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. Michael Taylor 60,161 Reputation points
    2021-04-15T13:53:31.027+00:00

    Use the Except method to return everything in one list that is not in the second list.

       var listA = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };  
       var listB = new[] { 2, 4, 6, 8, 10, 12, 14 };  
         
       var listC = listA.Except(listB);  
    

    Note that it uses equality comparison, like Union and other methods, so it is possible you'll need to define a custom IEqualityComparer implementation to do the comparison based upon the rules you want to use.

    In your case you're trying to do this via a join. As discussed in the docs join is equality only. To do a non-equality you can refer to this article but I think Except is easier.

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.