通過字段中選擇屬性我有一個對象Record
集團使用LINQ
它包含以下屬性:
Guid RecordId
Guid UserId
現在我必須做出分組並使用此Linq查詢:
Records.GroupBy(m => m.User)
問題是User
對象從2個地方填充,有時數據不匹配的屬性,從而產生具有用於單一UserId
例如多個結果:
List<Record>
{
new Record
{
RecordId = 1,
User = new User
{
UserId = 1,
UserName = '1',
OtherProperty = false
}
UserId = 1
},
new Record
{
RecordId = 2,
User = new User
{
UserId = 1,
UserName = '1',
OtherProperty = true
}
UserId = 1
},
new Record
{
RecordId = 3,
User = new User
{
UserId = 2,
UserName = '2',
OtherProperty = false
}
UserId = 2
}
}
的OtherProperty
是在User
對象的不同,導致沒有被分組。
我需要一個User
對象的分組,但實際上使用UserId
作爲分組字段。
問題是,這是我現在有:'的IEnumerable>',但你的方法,我得到這樣的結果:'的IEnumerable >'。我失去了'用戶'鍵。我想'User'作爲關鍵詞,但是'UserId'作爲groupby選擇器。 –
YesMan85
如果是這樣的話,那麼你需要寫一個'User'的相等比較爲(僞):'return u1.UserID == u2.UserID;'。在你做完這些之後,你將能夠'GroupBy'用戶。 –
請問爲什麼,如果你有'Record'作爲值,'Record'包含'User',你想讓用戶自己成爲分組鍵? –