문제

내가 종종 있을 정렬하는 사전 구성된 키와 값으로 값입니다.예를 들어,내가 해시의 단어와 해당 주파수는 주문하고 싶에 의 주파수이다.

SortedList 는 단일 값(말파),고 싶지도 그것을 다시하는 단어입니다.

SortedDictionary 주문 열쇠에 의하여지는 값이다.일부 리조트 사용자 정의 클래스, 하시기 바랍니다,청소기는 방법?

도움이 되었습니까?

해결책

를 사용:

using System.Linq.Enumerable;
...
List<KeyValuePair<string, string>> myList = aDictionary.ToList();

myList.Sort(
    delegate(KeyValuePair<string, string> pair1,
    KeyValuePair<string, string> pair2)
    {
        return pair1.Value.CompareTo(pair2.Value);
    }
);

당신을 대상으로 합니다.NET2.0 나 위의 단순화할 수 있습니다 이것으로 람다는 구문을-그것은 동일하지만,짧습니다.면을 대상으로 합니다.NET2.0 에만 사용할 수 있습니다 이 구문을 사용하는 경우 컴파일러를 Visual Studio2008 에서(또는 그 이상).

var myList = aDictionary.ToList();

myList.Sort((pair1,pair2) => pair1.Value.CompareTo(pair2.Value));

다른 팁

사용 LINQ:

Dictionary<string, int> myDict = new Dictionary<string, int>();
myDict.Add("one", 1);
myDict.Add("four", 4);
myDict.Add("two", 2);
myDict.Add("three", 3);

var sortedDict = from entry in myDict orderby entry.Value ascending select entry;

이것은 또한 허용한 유연성을 선택할 수 있는 최고 10,20 10%,etc.거나 사용하는 경우의 단어 주파수 인덱스 type-ahead, 에,당신은 또한 포함할 수 있습니다 StartsWith 절니다.

var ordered = dict.OrderBy(x => x.Value);

주위를 둘러보고 일부를 사용하여 C#3.0 기능을 우리는 작업을 수행 할 수 있습니다:

foreach (KeyValuePair<string,int> item in keywordCounts.OrderBy(key=> key.Value))
{ 
    // do something with item.Key and item.Value
}

이는 가장 깨끗한 방법으로 본와 유사한 방법으로는 루비의 처리시요.

정렬할 수 있습어 사전 의 값을 저장 자체를 다시(도록할 때 foreach 통해 그것의 값 순서대로 나올):

dict = dict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

지,그것을 정확하지 않을 수 있습니다,하지만 그것을 작동합니다.

높은 수준에서,당신은 다른 선택의 여지가 없음을 통해 걸어 전체적인 사전에서 보면 각각의 값입니다.

어쩌면 이것은:http://bytes.com/forum/thread563638.html 복사/붙여넣기에서 존 Timney:

Dictionary<string, string> s = new Dictionary<string, string>();
s.Add("1", "a Item");
s.Add("2", "c Item");
s.Add("3", "b Item");

List<KeyValuePair<string, string>> myList = new List<KeyValuePair<string, string>>(s);
myList.Sort(
    delegate(KeyValuePair<string, string> firstPair,
    KeyValuePair<string, string> nextPair)
    {
        return firstPair.Value.CompareTo(nextPair.Value);
    }
);

할 수 없을 정렬하는 사전 anyway.그들은 실제로 정렬됩니다.보증을 위해 사전 수 있는 키와 값의 컬렉션을 반복 가능한,값에 의해 검색할 수 있는 인덱스 또는 열쇠지만,의 보장은 없습니다 어떤 특별한 순서입니다.따라서 필요한 이름은 값 쌍으로 목록입니다.

를 정렬하지 않는 항목에서는 사전에 있습니다.사전 등습니다.NET 로 구현되는 해시 테이블-이 데이터 구조로 정렬에 의해 정의합니다.

필요하신 경우에는 반복할 수 있게 되 컬렉션(주)-당신은 당신을 사용할 필요가 SortedDictionary 으로 구현되는 이진 검색 나무입니다.

귀하의 경우에는,그러나 원본 구조로는 무관하기 때문에,그것은 순서로 정렬된 다른 분야이다.당신은 여전히 필요하다는 주파수에 의해서 새로운 컬렉션을 정하여 관련 분야(주파수).그래서 이 컬렉션에서 주파수는 키와 단어는 값입니다.이 단어가 동일한 주파수(그리고 당신은 그것을 사용하 키로)사용할 수 없습니다 둘 사전나 SortedDictionary(그들이 필요로 하는 독특한 키).나는 또한 당신이 당신 다음 코드 예제에서는 만들.

나는 당신을 유지를 주장에 대한 링크는 원래 항목에서의 메인/최초 사전입니다.

는 경우에있는 개체를 수집했고 더 복잡한 구조(더 필드)그리고 당신이 필요할 수 있을 효율적으로 액세스/종 사용하여 여러 가지 다양한 분야로 키-당신은 아마 사용자 지정 하는 데이터 구조로 구성됩의 메인 스토리지 지원하는 O(1)삽입 및 제거(LinkedList)및 여러 인덱싱 구조가-사전/SortedDictionaries/SortedLists.이러한 인덱스를 사용하는 것이 하나의 필드에서 당신의 복잡한 클래스로 키와 포인터/을 참조하여 LinkedListNode 에 LinkedList 으로 값입니다.

당신을 조정해야 삽입 및 제거를 유지하는 인덱스에서의 동기와 주요 컬렉션(LinkedList)및 제거 꽤 비싼 것이 나는 생각한다.이것은 비슷한 방법 데이터베이스는 인덱스 작업들에 대한 조회 하지만 그들은 부담이 될를 수행할 필요가 있을 때 많은 insetions 및 삭제.

위의 모든 것만이 정당화하려는 경우 몇 가지 보이-무거운 처리합니다.만 필요한 경우 출력하는 한 번 그들을 정렬된 주파수에 의해 다음 당신의 목록을 생성(익명)tuples:

var dict = new SortedDictionary<string, int>();
// ToDo: populate dict

var output = dict.OrderBy(e => e.Value).Select(e => new {frequency = e.Value, word = e.Key}).ToList();

foreach (var entry in output)
{
    Console.WriteLine("frequency:{0}, word: {1}",entry.frequency,entry.word);
}
Dictionary<string, string> dic= new Dictionary<string, string>();
var ordered = dic.OrderBy(x => x.Value);
return ordered.ToDictionary(t => t.Key, t => t.Value);

또는 재미를위한 당신이 사용할 수 있습 LINQ 확장자의 장점:

var dictionary = new Dictionary<string, int> { { "c", 3 }, { "a", 1 }, { "b", 2 } };
dictionary.OrderBy(x => x.Value)
  .ForEach(x => Console.WriteLine("{0}={1}", x.Key,x.Value));

정렬 값이

이 방법을 보여 정렬 값에서 사전입니다.우리가 보는 콘솔 프로그램 컴파일할 수 있습니다 Visual Studio 에서 실행됩니다.그가 사전 다음 종류에 의해 그들을 자신의 값이 있습니다.을 기억하는 사전에 인스턴스가 처음서로 정렬된 모든 방법입니다.우리가 사용하는 LINQ orderby 키워드 질의문에.

절 OrderBy 프로그램을 종류를 사전에[C#]

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        // Example dictionary.
        var dictionary = new Dictionary<string, int>(5);
        dictionary.Add("cat", 1);
        dictionary.Add("dog", 0);
        dictionary.Add("mouse", 5);
        dictionary.Add("eel", 3);
        dictionary.Add("programmer", 2);

        // Order by values.
        // ... Use LINQ to specify sorting by value.
        var items = from pair in dictionary
                orderby pair.Value ascending
                select pair;

        // Display results.
        foreach (KeyValuePair<string, int> pair in items)
        {
            Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
        }

        // Reverse sort.
        // ... Can be looped over in the same way as above.
        items = from pair in dictionary
        orderby pair.Value descending
        select pair;
    }
}

출력

dog: 0
cat: 1
programmer: 2
eel: 3
mouse: 5

분류 SortedDictionary 목록 묶로 ListView 를 사용하여 제어 VB.NET:

Dim MyDictionary As SortedDictionary(Of String, MyDictionaryEntry)

MyDictionaryListView.ItemsSource = MyDictionary.Values.OrderByDescending(Function(entry) entry.MyValue)

Public Class MyDictionaryEntry ' Need Property for GridViewColumn DisplayMemberBinding
    Public Property MyString As String
    Public Property MyValue As Integer
End Class

XAML:

<ListView Name="MyDictionaryListView">
    <ListView.View>
        <GridView>
            <GridViewColumn DisplayMemberBinding="{Binding Path=MyString}" Header="MyStringColumnName"></GridViewColumn>
            <GridViewColumn DisplayMemberBinding="{Binding Path=MyValue}" Header="MyValueColumnName"></GridViewColumn>
         </GridView>
    </ListView.View>
</ListView>

을 얻을 수있는 가장 쉬운 방법은 정는 사전을 사용하는 것에 내장 SortedDictionary 클래스:

//Sorts sections according to the key value stored on "sections" unsorted dictionary, which is passed as a constructor argument
System.Collections.Generic.SortedDictionary<int, string> sortedSections = null;
if (sections != null)
{
    sortedSections = new SortedDictionary<int, string>(sections);
}

sortedSections 이 포함 버전 정렬 sections

다른 답변은 좋은 경우,모든 당신이 원하는""임시 목록을 정렬 값입니다.그러나,당신이 할 경우 사전에 의해 정렬 Key자동으로 동기화 다른 사전에 의해 정렬 Value, 를 사용할 수 있습니다 Bijection<K1, K2> 클래스.

Bijection<K1, K2> 할 수 있를 초기화하는 컬렉션은 두 개의 기존 사전의,그래서 당신이 원하는 경우 그들 중 하나를 정렬하지 않고,그리고 당신이 원하는 다른 하나를 정렬을 만들 수 있습니다 당신의는 다음과 같은 코드를 사용하여 bijection

var dict = new Bijection<Key, Value>(new Dictionary<Key,Value>(), 
                               new SortedDictionary<Value,Key>());

당신이 사용할 수 있는 dict 모든 정상적인 사전에(그것을 구현하는 IDictionary<K, V>음),전화 dict.Inverse 을 얻을"역"사전에 의해 정렬 Value.

Bijection<K1, K2> 의 일부입 Loyc.Collections.dll, 하지만 당신이 원하는 경우에,당신은 단순히 수 복사 소스 코드 으로 자신만의 프로젝트입니다.

참고:이 있는 경우에 여러 개의 키와 동일한 값을 사용할 수 없습니다 Bijection, 지만,당신 수동으로 동기화 사이에 일반 Dictionary<Key,Value>BMultiMap<Value,Key>.

가 있다고 가정으로 사전

   Dictionary<int, int> dict = new Dictionary<int, int>();
   dict.Add(21,1041);
   dict.Add(213, 1021);
   dict.Add(45, 1081);
   dict.Add(54, 1091);
   dict.Add(3425, 1061);
   sict.Add(768, 1011);

1)사용할 수 있는 temporary dictionary to store values as :

        Dictionary<int, int> dctTemp = new Dictionary<int, int>();

        foreach (KeyValuePair<int, int> pair in dict.OrderBy(key => key.Value))
        {
            dctTemp .Add(pair.Key, pair.Value);
        }

실제로 C#에서 사전을 찾을 수 있을 정렬()메서드 당신은 더 많은 관심으로 정렬 값 당신의 값을 제공할 때까지 그들을 키, 즉,당신은 필요한 반복을 통해,그들을 LINQ 를 사용하기,

var items = new Dictionary<string, int>();
items.Add("cat", 0);
items.Add("dog", 20);
items.Add("bear", 100);
items.Add("lion", 50);

// Call OrderBy method here on each item and provide them the ids.
foreach (var item in items.OrderBy(k => k.Key))
{
    Console.WriteLine(item);// items are in sorted order
}

중 하나를 수행할 수 있습니다릭,

var sortedDictByOrder = items.OrderBy(v => v.Value);

var sortedKeys = from pair in dictName
            orderby pair.Value ascending
            select pair;

도의 종류에 따라 달라집하고 있는 값을 저장,
그것은 단 하나(다음과 같 string,int)또는 여러(트,배열,사용자 정의 등),
는 경우 단일을 만들 수 있는 목록은 그것의 적용을 정렬합니다.
는 경우 사용자 정의 클래스 그는 클래스를 구현해야 합니다 IComparable
ClassName: IComparable<ClassName> 과 재정의 compareTo(ClassName c) 그들은 더 이상 빠른 LINQ,그리고 더 많은 개체 지향합니다.

을 정렬할 수 있습어 사전 의 값을 얻을 결과에서는 사전을 사용하여 아래 코드:

Dictionary <<string, string>> ShareUserNewCopy = 
       ShareUserCopy.OrderBy(x => x.Value).ToDictionary(pair => pair.Key,
                                                        pair => pair.Value);                                          

주어진 당신이 사전에 정렬할 수 있습니다들에 직접 사용하여 값을 아래 중 하나는 라이너:

var x = (from c in dict orderby c.Value.Order ascending select c).ToDictionary(c => c.Key, c=>c.Value);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top