如何在另一个列表的基础上从一个列表中获取 [英] how to get from one List on the bases of another List

查看:58
本文介绍了如何在另一个列表的基础上从一个列表中获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好2全部...

我有2个相同类型的通用列表... FirstList包含从SupplierTable中获取的所有可能值..而SecondList包含从ItemTable中获取的一些选定供应商的值(即,特定项目的所有那些Suppliers .....

现在我想从FirstList中提取出Secondlist中不存在的所有值?
我该怎么办??

Muhammad Tufail ...

Hello 2 All...

i have 2 Generic Lists of the same type... FirstList Contains all the possible values getting from SupplierTable.. while the SecondList conatains some selected values of suppliers getting from ItemTable( i.e All those Suppliers for a specific item).....

Now i want to exract all values from FirstList which do not exist in the Secondlist????

what should i do for this???

Muhammad Tufail...

推荐答案

您可以使用Contains来做到这一点.我知道这似乎是违反直觉的,但是如果您将Contains反转,它将变为not contains.因此,您可能会有类似以下的代码:
You can use Contains to do this. I know it seems counter-intuitive, but if you invert Contains, it becomes not contains. So, you could have code that looks like this:
var myList = from c in firstList
    where !secondList.Contains(c.supplierId)
    select c; 


只需遍历第二个列表,然后从第一个列表中删除那里的项目.也许像这样:

Just iterate over the second List and remove the items you have there from the first list. Maybe like this:

List<T> firstList;
List<T> secondList;
foreach (T t in secondList){
  firstList.remove(t);
}



这应该可以解决问题(如果项目确实相等).当然,您必须插入自己的类型和变量名.

现在,如果项目不是真正相等,则需要您自己检查一下.试试这样的



That should do the trick (If the items are truly equal). Of course you have to plugin your own types and variable names.

Now if the items are not really equal you need to check that for yourself. Try something like this

foreach (DataType supplierToRemove in secondList) {
  int supplierID = supplierToRemove.ID;
  DataType delete = null;
  foreach (DataType supplier in firstList){
    if(supplier.ID == supplierID){
      delete = supplier;
      break;
    }
  }
  if (delete != null)
    firstList.remove(delete);
}



请注意,我不知道您的代码!您必须根据需要调整此解决方案.如果您没有ID,请改用表格的主键.



Be aware that I don''t know your code! You have to adapt this solution to your needs. If you do not have an ID, use your Primary Key of the Table instead.


请尝试以下操作,它可以帮助您解决问题,

Could you please try following, it might help you to sort out the issue,

var firstList = new List<string>() { "A", "B", "C" };
var secondList = new List<string>() { "A", "B" };
var resultList = firstList.Except(secondList);



谢谢:)



Thanks :)


这篇关于如何在另一个列表的基础上从一个列表中获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆