Skip to main content
 首页 » 编程设计

c#之比较两个列表并返回不匹配的项目结果错误

2024年02月06日12lhb25

我尝试使用 Except 方法比较两个列表。但是当我这样做时,我收到一条错误消息:

Cannot convert from 'Systems.Collections.Generic.List<>' to 'System.Linq.IQueryable<>'

'System.Collections.Generic.List<> does not contain a definition for 'Except' and the best extension method overload 'System.Linq.Queryable.Except(System.Linq.IQueryable, System.Collections.GEneric.IEnumerable)' has some invalid arguments

我在尝试 Intersect 时也遇到过这种情况。我正在尝试比较发送列表和结果列表(如下所示的代码和列表)并返回没有任何匹配项的项目。因此,当我在谷歌上搜索如何执行此操作时,我遇到了 Except 方法和 Intersect 方法。

public class Sent 
{ 
    public string Address; 
    public string Data; 
} 
 
public class Result 
{ 
    public string AddressOK; 
    public string DataOK; 
} 
 
 
 
var sent = new List<Sent>(); 
sent.Add(new Sent() { Address = linaddr1, Data = lindat1 }); 
var res = new List<Result>(); 
res.Add( new Result() { AddressOK = linaddr2, DataOK = lindat2 } ); 
//linaddr1 and 2, lindat1 and 2 contains the address and data shown in the list below 
//taken from another part of the entire program 

列表看起来像这样:

sent                       res 
Address    Data            Address        Data 
04004C     55AA55          04004C         55AA55 
040004     0720            040004         0720 
040037     30            
04004A     FFFF            04004A         FFFF 

我只试过使用这段代码: var diff = sent.Except(res).ToList() 但正如我所提到的,它会导致上述错误。

编辑:我编辑了列表。对不起。这只是 res 列表缺少原始列表中的一个或两个或多个项目,然后比较两个列表以查看 res 列表中缺少哪个项目的问题。

请您参考如下方法:

使用任何:

using System; 
 
using System.Collections.Generic; 
using System.Linq; 
 
public class Program 
{ 
    public static void Main() 
    { 
 
        var sent = new List<Sent>() 
        { 
            new Sent { Address = "04004C", Data = "55AA55" }, 
            new Sent { Address = "040004", Data = "0720" },              
            new Sent { Address = "040037", Data = "31" },                
            new Sent { Address = "04004A", Data = "FFFF" } 
        }; 
 
 
        var res = new List<Result> () { 
            new Result { AddressOK = "04004C", DataOK = "55AA55" }, 
            new Result { AddressOK = "040004", DataOK = "0721" },                
            new Result { AddressOK = "040038 ", DataOK = "31" },                 
            new Result { AddressOK = "04004A", DataOK = "FFFF" } 
 
        }; 
 
        var diff = 
            sent.Where (s => !res.Any (r => s.Address == r.AddressOK && s.Data == r.DataOK )); 
 
 
        foreach (var item in diff)  
        { 
            Console.WriteLine("{0} {1}", item.Address, item.Data); 
        } 
 
    } 
} 
 
 
public class Sent 
{ 
    public string Address; 
    public string Data; 
} 
 
 
public class Result 
{ 
    public string AddressOK; 
    public string DataOK; 
} 

输出:

040004 0720 
040037 31 

在线代码:https://dotnetfiddle.net/ZVuiPd