한 목록을 다른 목록으로 정렬
두 개의 목록 개체가 있습니다. 하나는 정수 목록이고 다른 하나는 개체 목록이지만 개체에는 ID 속성이 있습니다.
내가하고 싶은 것은 int 목록과 동일한 정렬 순서로 ID별로 개체 목록을 정렬하는 것입니다.
나는 잠시 동안 놀아 왔고 지금은 그것을 작동 시키려고 노력했지만 지금까지 기쁨은 없었습니다.
여기 내가 지금까지 가지고있는 것이 ...
//**************************
//*** Randomize the list ***
//**************************
if (Session["SearchResultsOrder"] != null)
{
// save the session as a int list
List<int> IDList = new List<int>((List<int>)Session["SearchResultsOrder"]);
// the saved list session exists, make sure the list is orded by this
foreach(var i in IDList)
{
SearchData.ReturnedSearchedMembers.OrderBy(x => x.ID == i);
}
}
else
{
// before any sorts randomize the results - this mixes it up a bit as before it would order the results by member registration date
List<Member> RandomList = new List<Member>(SearchData.ReturnedSearchedMembers);
SearchData.ReturnedSearchedMembers = GloballyAvailableMethods.RandomizeGenericList<Member>(RandomList, RandomList.Count).ToList();
// save the order of these results so they can be restored back during postback
List<int> SearchResultsOrder = new List<int>();
SearchData.ReturnedSearchedMembers.ForEach(x => SearchResultsOrder.Add(x.ID));
Session["SearchResultsOrder"] = SearchResultsOrder;
}
요점은 사용자가 회원을 검색 할 때 처음에는 무작위 순서로 표시되고 2 페이지를 클릭하면 해당 순서를 유지하고 다음 20 개의 결과가 표시된다는 것입니다.
Linq.OrderBy 절에서 매개 변수로 사용할 수있는 ICompare에 대해 읽었지만 간단한 예제를 찾을 수 없습니다.
우아하고 매우 간단한 LINQ 스타일 솔루션을 원하고 있습니다.
도움을 주시면 감사하겠습니다.
또 다른 LINQ 접근 방식 :
var orderedByIDList = from i in ids
join o in objectsWithIDs
on i equals o.ID
select o;
한 가지 방법 :
List<int> order = ....;
List<Item> items = ....;
Dictionary<int,Item> d = items.ToDictionary(x => x.ID);
List<Item> ordered = order.Select(i => d[i]).ToList();
이 정확한 질문에 대한 대답은 아니지만 배열 이 두 개인 경우 Array.Sort
배열을 정렬하고 '키'로 사용할 배열을 사용 하는 오버로드 가 있습니다.
https://msdn.microsoft.com/en-us/library/85y6y2d3.aspx
Array.Sort 메서드 (Array, Array)
각 키의 IComparable 구현을 사용하여 첫 번째 Array의 키를 기반으로 한 쌍의 1 차원 Array 개체 (하나는 키를 포함하고 다른 하나는 해당 항목을 포함 )를 정렬합니다.
Join
정확한 정수로 일치시키려는 경우 가장 적합한 후보입니다 (일치하는 항목이 없으면 빈 시퀀스가 표시됨). 다른 목록의 정렬 순서 만 얻고 싶다면 (두 목록의 요소 수가 동일하다면) Zip 을 사용할 수 있습니다 .
var result = objects.Zip(ints, (o, i) => new { o, i})
.OrderBy(x => x.i)
.Select(x => x.o);
꽤 읽기 쉽습니다.
Here is an extension method which encapsulates Simon D.'s response for lists of any type.
public static IEnumerable<TResult> SortBy<TResult, TKey>(this IEnumerable<TResult> sortItems,
IEnumerable<TKey> sortKeys,
Func<TResult, TKey> matchFunc)
{
return sortKeys.Join(sortItems,
k => k,
matchFunc,
(k, i) => i);
}
Usage is something like:
var sorted = toSort.SortBy(sortKeys, i => i.Key);
One possible solution:
myList = myList.OrderBy(x => Ids.IndexOf(x.Id)).ToList();
Note: use this if you working with In-Memory
lists, doesn't work for IQueryable
type, as IQueryable
does not contain a definition for IndexOf
참고URL : https://stackoverflow.com/questions/3945935/sort-one-list-by-another
'program tip' 카테고리의 다른 글
JQuery Datatables : 정의되지 않은 'aDataSort'속성을 읽을 수 없습니다. (0) | 2020.10.26 |
---|---|
기본 잠금 화면을 통한 Android 활동 (0) | 2020.10.26 |
수정 : 글로벌 요소 'configuration'이 이미 선언되었습니다. (0) | 2020.10.25 |
Storyboard에서 UIButton BorderColor 변경 (0) | 2020.10.25 |
C #에서 foreach 루프 종료 (0) | 2020.10.25 |