devc2 February 2016

How to match two Lists with only items that are different in Linq

I have a StudentData class

public class StudentData
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string Surname { get; set; }
    public int? Bonus { get; set; }
    public int? Subject1Mark { get; set; }
    public int? Subject2Mark { get; set; }
    public int? Subject3Mark{ get; set; }
}

Each student has a unique Id that identifies him

I have a List<StudentData> CurrentData that has data of

1, John, Smith, 10, 50 ,50 ,50

2, Peter, Parker, 10, 60 ,60 ,60

3, Sally, Smart, 10, 70 ,70 ,70

4, Danny, Darko, 20, 80, 80, 80

I then have a List<StudentData> DataToUpdate which only contains the Id and Marks fields. Not the other fields.

1, null, null, null, 50 ,50 ,50

2, null, null, null, 65, 60 ,60

3, null, null, null, 70 ,70 ,70

The Ids of the list are not necessary in the same order

If you compare the two lists only Peter Parker's marks have changed in one subject.

I want to get the output to return

2, Peter, Parker, 10, 65 ,60 ,60

I want to takeList<StudentData> CurrentData inner join this with List<StudentData> DataToUpdate but only where marks are different

So in SQL it want the following

SELECT
CurrentData.Id,
CurrentData.FirstName ,
CurrentData.Surname,
CurrentData.Bonus,
DataToUpdate.Subject1Mark,
DataToUpdate.Subject2Mark,
DataToUpdate.Subject3Mark
FROM CurrentData
INNER JOIN DataToUpdate
ON CurrentData.Id= DataToUpdate.Id
AND (
    CurrentData.Subject1Mark<> DataToUpdate.Subject1Mark
    OR
    CurrentData.Subject2Mark<> DataToUpdate.Subject2Mark
    OR
    CurrentData.Subject3Mark<> DataToUpdate.Subject3Mark
)

      

Answers


dasblinkenlight February 2016

The structure of LINQ query looks very similar to SQL:

var res =
    from cur in CurrentData
    join upd in DataToUpdate on upd.Id equals cur.Id
    where (cur.Subject1Mark != upd.Subject1Mark || cur.Subject2Mark != upd.Subject2Mark || cur.Subject3Mark != upd.Subject3Mark)
    select new {
        Current = cur
    ,   UpdatedSubject1Mark = upd.Subject1Mark
    ,   UpdatedSubject2Mark = upd.Subject2Mark
    ,   UpdatedSubject3Mark = upd.Subject3Mark
    };

The main difference is that filtering out by inequality has moved from the on clause in SQL to a where clause of LINQ.

Post Status

Asked in February 2016
Viewed 2,068 times
Voted 9
Answered 1 times

Search




Leave an answer