Linq to SQL 是 .NET Framework 提供的一种对象关系映射(ORM)技术,它允许开发者使用 LINQ 查询语法直接操作 SQL Server 数据库。
要在 Linq to SQL 中选择不同的行并忽略特定列,可以使用以下几种方法:
var distinctResults = dbContext.YourTable
.Select(x => new
{
x.Column1,
x.Column2,
// 只包含你需要的列,忽略其他列
})
.Distinct()
.ToList();
如果需要基于特定列判断行的唯一性:
var distinctResults = dbContext.YourTable
.GroupBy(x => new { x.Column1, x.Column2 }) // 按需要比较的列分组
.Select(g => g.First()) // 从每组中取第一条记录
.ToList();
// .NET 6+ 或使用 MoreLINQ 库
var distinctResults = dbContext.YourTable
.DistinctBy(x => new { x.Column1, x.Column2 })
.ToList();
假设有一个 Products 表,我们想获取不重复的 CategoryID 和 SupplierID,忽略其他列:
using (var db = new YourDataContext())
{
var distinctProducts = db.Products
.Select(p => new
{
p.CategoryID,
p.SupplierID
})
.Distinct()
.ToList();
foreach (var product in distinctProducts)
{
Console.WriteLine($"Category: {product.CategoryID}, Supplier: {product.SupplierID}");
}
}
这种方法既实现了行的去重,又忽略了不需要的列。
没有搜到相关的文章