我有一個代表用戶的類陣列和另一個代表固定專案的類陣列(目前只有用戶ID)。以下是課程:
public class User
{
public int UserId { get; set; }
public bool Pinned { get; set; }
public User(int userId, bool pinned)
{
UserId = userId;
Pinned = pinned;
}
}
public class PinnedItem
{
public int UserId { get; set; }
public PinnedItem(int userId)
{
UserId = userId;
}
}
固定用戶的所有用戶 ID 都以特定順序(固定專案的順序)保存,我想對用戶陣列進行排序,以便固定用戶位于頂部,并且這些固定用戶遵循固定專案陣列的順序。例如,如果我有一組用戶,例如:
var users = new []{ new User(1, true), new User(2, false), new User(3, true) }
和一個看起來像這樣的固定專案陣列:
var pinnedItems = new [] { new PinnedItem(3), new PinnedItem(1) }
然后我希望得到的陣列看起來像這樣:
[ {3, true}, {1, true}, {2, false} ]
如果固定專案的陣列沒有任何順序,我也需要它來作業。所以如果我有這個用戶陣列:
var users = new []{ new User(1, false), new User(2, true), new User(3, true), new User(4, true) }
和這個固定專案陣列:
var pinnedItems = new [] { new PinnedItem(3), new PinnedItem(2), new PinnedItem(4) }
在這種情況下,我希望生成的陣列如下所示:
[ {3, true}, {2, true}, {4, true}, {1, false} ]
任何形式的幫助將不勝感激。此外,如果問題中有任何不清楚的地方,我很抱歉,如果需要,我會進行相應的編輯。
uj5u.com熱心網友回復:
這有點邋遢,但這樣的事情會做到這一點:
var joined =
users
.GroupJoin(pinnedItems, u => u.UserId, p => p.UserId, (u, p) => new { u.UserId, Pinned = p.Any() })
.OrderByDescending(r => r.Pinned)
.ThenByDescending(r => r.UserId)
.ToList();
您可以調整投影和排序以獲得您想要的結果。
uj5u.com熱心網友回復:
我確定有很多方法可以做到這一點,我還有很多 LINQ 需要學習,但以下內容應該可以幫助您入門;
// First, get the users that are mentioned by a PinnedItem
var pinnedUsers = pinnedItems.Select(x => users.FirstOrDefault(y => y.UserId == x.UserId));
// Get all the users that are not mentioned in a PinnedItem
var unpinnedUsers = users.Except(pinnedUsers);
// Combine both
var both = pinnedUsers.Concat(unpinnedUsers);
uj5u.com熱心網友回復:
如果有人偶然發現這篇文章,這是一個針對更大陣列優化的解決方案(如果您知道不會有很多固定專案,@Fixation 發布的答案完全可以):
Dictionary<int, int?> positionByUserId = pinnedItems
.Select((i, index) => new { i.UserId, Position = index })
.ToDictionary(x => x.UserId, x => (int?)x.Position);
var result = users
.Select(u => new
{
User = u,
Position = positionByUserId.GetValueOrDefault(u.UserId) ?? int.MaxValue
})
.OrderBy(x => x.Position)
.Select(x => x.User)
.ToArray();
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/482220.html
上一篇:回傳Java年齡第二年輕的串列
