Filter Out List with another list using LINQ

↘锁芯ラ 提交于 2020-12-26 12:17:08

问题


Hi I'm having difficulty finding an answer to my question here, so I figured I'd just ask. I have to lists of classes, ServiceItem, and ServiceDetailsClass. I want to filter out all of the ServiceDetailClass Items that are not int ServiceItems list. Here are the two classes:

public class ServiceItem
{
    public long ID { get; set; }
    public string Status { get; set; }
}

public class ServiceDetailsClass
{
    public string Name;
    public long ID;
    public int Quantity;
    public string Notes;
    public string Status;
    public string Description;
    public DateTime CreatedDate;
}

So far the only things I've found on here is for lists that have a list in them, so this is a bit different. This is all I was able to come up with, but the filter list has 0 item, even though I know it should have more than that:

lstFilteredServiceDetailsClass = lstServiceDetailsClass.Where(i => lstServiceItem.Contains
      (new ServiceItem { lngId = i.ServiceID, strStatus = "Locked" }) 

Any help is appreciated. Thanks!


回答1:


You're making a new object and then checking the list to see if that exact object/instance is in it (i.e. because it's an object, it's comparing the reference).

Instead, you need to look for overlapping IDs.

Something like this should work:

List<ServiceItem> serviceItems;
List<ServiceItemDetails> serviceItemDetails;

var result = serviceItemDetails.Where(sid => serviceItems.Any(si => si.ID == sid.ID))

In English: "The collection of ServiceItemDetails where the list of service items has an item with the same ID"



来源:https://stackoverflow.com/questions/41929102/filter-out-list-with-another-list-using-linq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!