0

## 想問下 LINQ 的 Distinct 和 OrderBy 的問題

``````var dt = (from t1 in db.AAA
where t1.bAAA_CANCEL == false
&& t1.cAAA_LEVEL == "C"
//orderby t1.cAAA_KIND, t1.iAAA_SEQ  //先排序再Distinct，會發生沒排序的錯誤
select new
{
t1.cAAA_TYPE,
t1.cAAA_KIND,
t1.cAAA_LEVEL,
//t1.iAAA_SEQ
}).Distinct()
.ToList().Select(t1 => new
{
cAAA_TYPE = t1.cAAA_TYPE,
cAAA_KIND = t1.cAAA_KIND,
cAAA_LEVEL = t1.cAAA_LEVEL,
iAAA_SEQ = (from t4 in db.AAA
where t4.bAAA_CANCEL == false
&& t4.cAAA_LEVEL == "C"
&& t4.cAAA_TYPE == t1.cAAA_TYPE
&& t4.cAAA_KIND == t1.cAAA_KIND
&& t4.cAAA_LEVEL == t1.cAAA_LEVEL
select t4.iAAA_SEQ).FirstOrDefault()
})
.OrderBy(t=>t.cAAA_KIND)
.ThenBy(t=>t.iAAA_SEQ)
.ToList();
``````
sion iT邦新手 4 級 ‧ 2019-07-18 15:42:59 檢舉

### 1 個回答

1

iT邦大師 1 級 ‧ 2019-07-18 17:11:54

``````select cAAA_TYPE,cAAA_KIND,cAAA_LEVEL
from AAA t1
group by cAAA_TYPE,cAAA_KIND,cAAA_LEVEL
order by cAAA_KIND,
(select top 1 t2.iAAA_SEQ from AAA t2 where t1.cAAA_TYPE = t2.cAAA_TYPE
and t1.cAAA_KIND = t2.cAAA_KIND and t1.cAAA_LEVEL = t2.cAAA_LEVEL)
``````

LINQ可以這樣寫

``````	var list = (
from t in AAAs
group t by new
{
t.CAAAtTYPE,
t.CAAAtKIND,
t.CAAAtLEVEL
} into t
orderby t.Key.CAAAtKIND, (from s in t
select s.IAAAtSEQ).First()
select t into s
select s.Key
).ToList();
``````

• 跟sion大大建議一樣,我會先嘗試使用SQL寫再寫成LINQ
• 不要還沒組出結果前就ToList這樣會變成LINQ Object而不是SQL,會撈取大量資料到AP端。