简体   繁体   English

从多个表linq到sql中选择Distinct

[英]Select Distinct from multiple tables linq to sql

I have tow tables, tblItem and tblInsertLines, in tblInsertLines I have the same ItemId but with differnt ProdDate and ExpireDate, I want to get a distinct list of all items but select the first row from tblInsertLines as the first row contains the oldest ProdDate. 我有两个表,tblItem和tblInsertLines,在tblInsertLines中,我具有相同的ItemId,但ProdDate和ExpireDate不同,我想获得所有项目的不同列表,但是从tblInsertLines中选择第一行,因为第一行包含最旧的ProdDate。 Any help will be appreciated. 任何帮助将不胜感激。 I use this code. 我使用此代码。

public static List<Item> getItemList()
    {
        using (var db = new AWarehouseDataClassesDataContext())
        {

            var list = (from i in db.tblItems
                        join e in db.tblInsertLines on i.ItemId equals e.ItemId 
                        orderby i.NameE
                        select new Item
                        {
                            code = i.Code,
                            itemId = i.ItemId,
                            lastUpdate = i.LastUpdate,
                            nameA = i.NameA,
                            nameE = i.NameE,
                            qty = i.Qty,
                            prodDate = e.ProdDate,
                            expireDate = e.ExpireDate,
                            updatedBy = i.UpdatedBy
                        }).Distinct();
            return list.ToList();
        }
    }

You can try 你可以试试

    var list= (from i in db.tblItems
                join e in db.tblInsertLines on i.ItemId equals e.ItemId 
                where e.counter > 0
                orderby i.NameE
                group new { i, e } by e.ItemId into g
                select new Item
                {
                    code = g.First().i.Code,
                    itemId = g.Key,
                    lastUpdate = g.First().i.LastUpdate,
                    nameA = g.First().i.NameA,
                    nameE = g.First().i.NameE,
                    qty = g.First().i.Qty,
                    prodDate = g.Min(x=>x.e.ProdDate),
                    expireDate = g.First().e.ExpireDate,
                    updatedBy = g.First().i.UpdatedBy
                }).ToList();

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

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