简体   繁体   English

使用LINQ将另一个列表过滤掉列表

[英]Filter Out List with another list using LINQ

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. 我必须列出类,ServiceItem和ServiceDetailsClass。 I want to filter out all of the ServiceDetailClass Items that are not int ServiceItems list. 我想过滤掉所有不是int ServiceItems列表的ServiceDetailClass项。 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: 这是我能够提出的所有内容,但是过滤器列表有0个项目,即使我知道它应该有更多:

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

Any help is appreciated. 任何帮助表示赞赏。 Thanks! 谢谢!

You're making a new object and then checking the list to see if that exact object/instance is in it (ie because it's an object, it's comparing the reference). 您正在创建一个新对象,然后检查列表以查看该对象/实例是否在其中(即因为它是一个对象,它正在比较该引用)。

Instead, you need to look for overlapping IDs. 相反,您需要查找重叠的ID。

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" 英文:“ServiceItemDetails的集合,其中服务项列表具有相同ID的项目”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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