Home > Software design >  Filter data from 2 lists with diferent models C#
Filter data from 2 lists with diferent models C#

Time:04-21

I have this models

public class RoutingAttributeModel
{
    public int Bus_No { get; set; }
    public int Attribute_No { get; set; }
    public string Attribute_Name { get; set; }
    public string Status { get; set; }
    public string Notes { get; set; }
}

public class AgentRoutingAttributeModel
{
    public int Agent_No { get; set; }
    public int Bus_No { get; set; }
    public int Attribute_No { get; set; }
    public string Attribute_Name { get; set; }
    public string Status { get; set; }
}

List<RoutingAttributeModel> lstComplete = new List<RoutingAttributeModel>();
List<AgentRoutingAttributeModel> lstAssigned = new List<AgentRoutingAttributeModel>();

Filled this with some data

Is it possible to filter with Linq? I want to save in a new list the diferent content between lstComplete and lstAssigned

I was trying to join both lists but got stuck there

var results1 = from cl in lstComplete 
                       join al in lstAssigned 
                       on cl.Attribute_No equals al.Attribute_No
                       select cl;

CodePudding user response:

you can use linq as my understanding, you try to find linked by attribute_No records and have a list of not matching properties?

lstComplete.Add(new RoutingAttributeModel(){
    Attribute_Name = "aaa",
    Attribute_No = 1,
    Bus_No = 1,
    Notes = "",
    Status = "status"
    });
    

    lstAssigned.Add(new AgentRoutingAttributeModel()
    {
    Attribute_No = 1,
    Agent_No = 10,
    Bus_No = 1,
    Attribute_Name = "bbb",
    Status = "status2"
    });

    var lst = lstComplete
       .Join(lstAssigned,
           complete => complete.Attribute_No,
           assigned => assigned.Attribute_No,
           (complete, assigned) => new { lstComplete = complete, lstAssigned = assigned })
               .Select(s => new { s.lstComplete, s.lstAssigned})
               .Where(w=> 
                    w.lstAssigned.Attribute_Name != w.lstComplete.Attribute_Name
                    || w.lstAssigned.Bus_No != w.lstComplete.Bus_No
               )
               .ToList()
               .Dump();
    

so result would be enter image description here

CodePudding user response:

You could try the following query

var filteredList = lstComplete
               .Where(x => !lstAssigned.Any(y => y.Attribute_No == x.Attribute_No));
  • Related