如何从数据表中选择不在 IEnumerable 中的数据

本文关键字:IEnumerable 数据 选择 数据表 | 更新日期: 2023-09-27 18:18:33

我有一个数据表dbcrs,我只想获取不在以下枚举中的数据:

IEnumerable<Crs> res

注意:两者中的键都是id

如何从数据表中选择不在 IEnumerable 中的数据

这是我

的建议:

var result = dbcrs.Where(item => res.FirstOrDefault(resItem => resItem.Id == item.Id) == null);
首先,

您需要使用 AsEnumerable() 来查询 DataTable 的 Rows 集合,然后使用 !Contains 作为 不像这样:

var query = from r in dbcrs.AsEnumerable()
        where !( from s in res select r.Id)
               .Contains(r.Id)
        select r;

使用 Except 和 IEquatable 执行此操作的示例<>

这种方式的好处是,您可以定义"等于"的含义,以便仍然可以使用可能具有相同 ID 但不相等的两个列表。

例如,您从两个表中获取数据,因此 Id 可以重复,但其他一些属性定义它们是否实际上相等。

class Crs:IEquatable<Crs>
        {
            public int Id { get; set; }
            public string Description { get; set; }
            public bool Equals(Crs other)
            {
                if (Object.ReferenceEquals(other, null)) 
                    return false;
                if (Object.ReferenceEquals(this, other)) 
                    return true;
                return Id.Equals(other.Id) && Description.Equals(other.Description);
            }
            public override int GetHashCode()
            {
                int hashId = Id.GetHashCode();
                int hashDescription = Description == null ? 0 : Description.GetHashCode();
                return hashId ^ hashDescription;
            }
        }
        internal static void RunMe()
        {
            var dataTable = new List<Crs>(){
                new Crs{Id=1, Description="First"},
                new Crs{Id=2, Description="Second"},
                new Crs{Id=5, Description="Fifth"}
            };
            var enumerable = new List<Crs>(){
                new Crs{Id=2, Description="Second"},
                new Crs{Id=4, Description="Fourth"}
            };
            var distinct = dataTable.Except(enumerable);
            distinct.ToList().ForEach(d => Console.WriteLine("{0}: {1}", d.Id, d.Description));
        }
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[]
        {
            new DataColumn("Id", typeof(System.Int32)),
            new DataColumn("Name", typeof(System.String))
        });
        dt.Rows.Add (new Object[]{1,"Test"});
        dt.Rows.Add(new Object[] {2, "Test" });

        var l = new Int32[] {  2, 4 };

        var l1 = dt.AsEnumerable().Where(p1 => Array.IndexOf(l, p1.Field<Int32>(0))<0).CopyToDataTable();

这将返回一行,因为在 Datatable 和数组中都有一个共同的值,即只有 2。 所以输出将是

2、测试

相关文章: