简体   繁体   中英

Select different objects from two collections

I have the following class:

struct UserRecord
{
    //--- common settings
    int               login;                      // login
    int               leverage;                   // leverage
    int               enable;                     // enable
}

And I have two lists:

List<UserRecord> base_data = new List<UserRecord>();

base_data.Add(new UserRecord(){login = 1, leverage = 1000, enable = 0});
base_data.Add(new UserRecord(){login = 2, leverage = 100, enable = 0});
base_data.Add(new UserRecord(){login = 3, leverage = 10, enable = 1});
base_data.Add(new UserRecord(){login = 4, leverage = 10000, enable = 0});

List<UserRecord> snapshot_data= new List<UserRecord>();

snapshot_data.Add(new UserRecord(){login = 1, leverage = 1000, enable = 1});
snapshot_data.Add(new UserRecord(){login = 2, leverage = 100, enable = 0});
snapshot_data.Add(new UserRecord(){login = 3, leverage = 10, enable = 1});
snapshot_data.Add(new UserRecord(){login = 4, leverage = 10000, enable = 1});

My goal is to filter the records, and get the two records in a new list, that are with different fields, in this case only the field 'enable' is different.

var filtered_data = new List<UserRecord>(); // here records with login 1 and 4 should go.

Do you have any suggestions?

You may look for Enumerable.Except() from System.Linq to find the differences between both enumerable.

using System.Linq;

List<UserRecord> filter_data = base_data.Except(snapshot_data)
            .ToList();

Demo @ .NET Fiddle


Another approach is if you just want to compare the difference in enable based on the items with the same login and leverage from the different lists.

You need to join both lists by the key(s) and query the record from the first list with the different enable value.

List<UserRecord> filter_data = (from a in base_data
                                join b in snapshot_data on new { a.login, a.leverage } equals new { b.login, b.leverage }
                                where a.enable != b.enable
                                select a
                                ).ToList();

Demo Solution 2 @ .NET Fiddle

You can use this linq to get what you want:

    List<UserRecord> filter_data = base_data
       .Where(x => !snapshot_data.Any(y => 
        y.login == x.login && 
        y.Leverage == x.Leverage && 
        y.enable == x.enable))
        .ToList();

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM