C LINQ中如何按實體的某個屬性去重

2022-06-25 18:30:14 字數 2646 閱讀 2602

net[c#]linq中如何按實體的某個屬性去重後返回不重複的集合?

比如有如下實體集合:

person1: id=1, name="test1"

person2: id=1, name="test1"

person3: id=2, name="test2"

如何使用linq按 person.id 去重,返回的集合只包含 person1 和 person3 ?

建立乙個靜態擴充套件類:

public static ienumerable distinctby

(this ienumerablesource, funckeyselector)

}}

呼叫方法:

var query = people.distinctby(p => p.id);

如果需要按多個屬性去重,則可以使用匿名物件,如:

var query = people.distinctby(p => new );

listdistinctpeople = allpeople

.groupby(p => p.personid)

.select(g => g.first())

.tolist();

多屬性去重:

listdistinctpeople = allpeople

.groupby(p => new )

.select(g => g.first())

.tolist();

var uniquepeople = from p in people

group p by new //or group by new

into mygroup

select mygroup.firstordefault();

persons.tolookup(p => p.id).select(coll => coll.first());
var result = people.where(p => !people.any(q => (p != q && p.id == q.id)));

1.你好?是因為你,身邊的人好。—— by瀟沫明月 -dont't repeat yourself 2.下輩子 無論 愛與不愛 我們 都不會 再見 3.有所見略同的對手 有對酒當歌的友人 有真心相對的紅顏 有識千里馬的伯樂 有一顆熾烈真誠的心 所以----- 要知道你最想做的 i will not repeat myself

net[c#]linq中如何按實體的某個屬性去重後返回不重複的集合?

比如有如下實體集合:

person1: id=1, name="test1"

person2: id=1, name="test1"

person3: id=2, name="test2"

如何使用linq按 person.id 去重,返回的集合只包含 person1 和 person3 ?

建立乙個靜態擴充套件類:

public static ienumerable distinctby

(this ienumerablesource, funckeyselector)

}}

呼叫方法:

var query = people.distinctby(p => p.id);

如果需要按多個屬性去重,則可以使用匿名物件,如:

var query = people.distinctby(p => new );

listdistinctpeople = allpeople

.groupby(p => p.personid)

.select(g => g.first())

.tolist();

多屬性去重:

listdistinctpeople = allpeople

.groupby(p => new )

.select(g => g.first())

.tolist();

var uniquepeople = from p in people

group p by new //or group by new

into mygroup

select mygroup.firstordefault();

persons.tolookup(p => p.id).select(coll => coll.first());
var result = people.where(p => !people.any(q => (p != q && p.id == q.id)));

JPA忽略實體類中的某個屬性,不持久化此屬性

使用jpa時,持久化實體類中的某個屬性沒有在資料庫欄位中,會出現一下錯誤 com.mysql.jdbc.exceptions.jdbc4.mysqlsyntaxerrorexception unknown column transtask0 parameter in field list 去掉 co...

List中根據class實體的某個屬性去重或排序

去重 根據alarmentity.class的乙個屬性sourceproblem去重,並保留最新 alarms是按照時間順序儲存的 private static listremoveduplicatealarms listalarms 為了保留最新,所以list需要使用reverse從後往前讀取 c...

mybatis中當實體的屬性和資料庫的屬性不一致時

實體的屬性 private long bookid 圖書id 資料庫中對應的為 book id private string bookname 圖書名稱 name private int number 數量 number實體類中的按戶型和資料庫中的屬性不一致,所以要新增對映關係 column 是資料...