我正在编写一个程序来设置一个序列,其中各种对象将出现在报告中。 序列是Excel电子表格中的Y位置(单元格)。
下面是代码的演示部分。 我想要完成的是拥有一个集合,这将允许我添加多个对象,我可以根据序列获得一个已排序的集合
SortedList list = new SortedList();
Header h = new Header();
h.XPos = 1;
h.name = "Header_1";
list.Add(h.XPos, h);
h = new Header();
h.XPos = 1;
h.name = "Header_2";
list.Add(h.XPos, h);
我知道SortedList不允许这样,我一直在寻找替代品。我不想消除重复项,并且已经尝试List<KeyValuePair<int, object>>
。
感谢。
答案 0 :(得分:65)
使用您自己的IComparer!
就像其他一些答案中已经说过的那样,你应该使用你自己的比较器类。为此,我使用了一个通用的IComparer类,它可以与任何实现IComparable的东西一起使用:
/// <summary>
/// Comparer for comparing two keys, handling equality as beeing greater
/// Use this Comparer e.g. with SortedLists or SortedDictionaries, that don't allow duplicate keys
/// </summary>
/// <typeparam name="TKey"></typeparam>
public class DuplicateKeyComparer<TKey>
:
IComparer<TKey> where TKey : IComparable
{
#region IComparer<TKey> Members
public int Compare(TKey x, TKey y)
{
int result = x.CompareTo(y);
if (result == 0)
return 1; // Handle equality as beeing greater
else
return result;
}
#endregion
}
您将在实例化新的SortedList,SortedDictionary等时使用它:
SortedList<int, MyValueClass> slist = new SortedList<int, MyValueClass>(new DuplicateKeyComparer<int>());
这里int是可以重复的密钥。
答案 1 :(得分:13)
您可以安全地使用List&lt;&gt; 。 List有一个Sort方法,其重载接受IComparer。您可以创建自己的分拣机类。这是一个例子:
private List<Curve> Curves;
this.Curves.Sort(new CurveSorter());
public class CurveSorter : IComparer<Curve>
{
public int Compare(Curve c1, Curve c2)
{
return c2.CreationTime.CompareTo(c1.CreationTime);
}
}
答案 2 :(得分:7)
最简单的解决方案(与上述所有方法相比):使用SortedSet<T>
,它接受IComparer<SortableKey>
类,然后以这种方式实现Compare方法:
public int Compare(SomeClass x, SomeClass y)
{
var compared = x.SomeSortableKeyTypeField.CompareTo(y.SomeSortableKeyTypeField);
if (compared != 0)
return compared;
// to allow duplicates
var hashCodeCompare = x.GetHashCode().CompareTo(y.GetHashCode());
if (hashCodeCompare != 0)
return hashCodeCompare;
if (Object.ReferenceEquals(x, y))
return 0;
// for weird duplicate hashcode cases, throw as below or implement your last chance comparer
throw new ComparisonFailureException();
}
答案 3 :(得分:5)
我使用以下内容:
public class TupleList<T1, T2> : List<Tuple<T1, T2>> where T1 : IComparable
{
public void Add(T1 item, T2 item2)
{
Add(new Tuple<T1, T2>(item, item2));
}
public new void Sort()
{
Comparison<Tuple<T1, T2>> c = (a, b) => a.Item1.CompareTo(b.Item1);
base.Sort(c);
}
}
我的测试用例:
[TestMethod()]
public void SortTest()
{
TupleList<int, string> list = new TupleList<int, string>();
list.Add(1, "cat");
list.Add(1, "car");
list.Add(2, "dog");
list.Add(2, "door");
list.Add(3, "elephant");
list.Add(1, "coconut");
list.Add(1, "cab");
list.Sort();
foreach(Tuple<int, string> tuple in list)
{
Console.WriteLine(string.Format("{0}:{1}", tuple.Item1,tuple.Item2));
}
int expected_first = 1;
int expected_last = 3;
int first = list.First().Item1; //requires using System.Linq
int last = list.Last().Item1; //requires using System.Linq
Assert.AreEqual(expected_first, first);
Assert.AreEqual(expected_last, last);
}
输出:
1:cab
1:coconut
1:car
1:cat
2:door
2:dog
3:elephant
答案 4 :(得分:3)
问题是数据结构设计不符合要求:有必要为相同的XPos存储多个Header。因此,SortedList<XPos, value>
的值不应为Header
,而应为List<Header>
。这是一个简单而小的改变,但它解决了所有问题并避免像其他建议的解决方案一样产生新问题(见下面的解释):
using System;
using System.Collections.Generic;
namespace TrySortedList {
class Program {
class Header {
public int XPos;
public string Name;
}
static void Main(string[] args) {
SortedList<int, List<Header>> sortedHeaders = new SortedList<int,List<Header>>();
add(sortedHeaders, 1, "Header_1");
add(sortedHeaders, 1, "Header_2");
add(sortedHeaders, 2, "Header_3");
foreach (var headersKvp in sortedHeaders) {
foreach (Header header in headersKvp.Value) {
Console.WriteLine(header.XPos + ": " + header.Name);
}
}
}
private static void add(SortedList<int, List<Header>> sortedHeaders, int xPos, string name) {
List<Header> headers;
if (!sortedHeaders.TryGetValue(xPos, out headers)){
headers = new List<Header>();
sortedHeaders[xPos] = headers;
}
headers.Add(new Header { XPos = xPos, Name = name });
}
}
}
Output:
1: Header_1
1: Header_2
2: Header_3
请注意添加&#34;搞笑&#34;关键,就像添加一个随机数或假装2个具有相同值的XPO不同导致许多其他问题。例如,删除特定的标题变得很困难甚至不可能。
另请注意,如果只需要对每List<Header>
个Header
进行排序,排序性能会更好。示例:如果有100个XPos且每个包含100个标题,则需要对10000 Header
进行排序,而不是100 List<Header>
。
当然,这个解决方案也有一个缺点:如果有许多只有1个标头的XPO,需要创建多个列表,这是一些开销。
答案 5 :(得分:2)
非常感谢你的帮助。在搜索更多时,我发现了这个解决方案。 (在其他问题的Stackoverflow.com中可用)
首先,我创建了一个类来封装我的对象(Headers,Footer等)
public class MyPosition
{
public int Position { get; set; }
public object MyObjects{ get; set; }
}
所以这个类应该保留在对象上,每个对象的PosX都是int Position
List<MyPosition> Sequence= new List<MyPosition>();
Sequence.Add(new MyPosition() { Position = 1, Headerobject });
Sequence.Add(new MyPosition() { Position = 2, Headerobject1 });
Sequence.Add(new MyPosition() { Position = 1, Footer });
League.Sort((PosA, PosB) => PosA.Position.CompareTo(PosB.Position));
最终得到的是排序的“序列”列表。
答案 6 :(得分:2)
此集合类将维护重复项并插入重复项的排序顺序。诀窍是使用唯一值标记项目 插入它们以保持稳定的排序顺序。然后我们把它全部包裹起来 ICollection接口。
public class SuperSortedSet<TValue> : ICollection<TValue>
{
private readonly SortedSet<Indexed<TValue>> _Container;
private int _Index = 0;
private IComparer<TValue> _Comparer;
public SuperSortedSet(IComparer<TValue> comparer)
{
_Comparer = comparer;
var c2 = new System.Linq.Comparer<Indexed<TValue>>((p0, p1) =>
{
var r = _Comparer.Compare(p0.Value, p1.Value);
if (r == 0)
{
if (p0.Index == -1
|| p1.Index == -1)
return 0;
return p0.Index.CompareTo(p1.Index);
}
else return r;
});
_Container = new SortedSet<Indexed<TValue>>(c2);
}
public IEnumerator<TValue> GetEnumerator() { return _Container.Select(p => p.Value).GetEnumerator(); }
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
public void Add(TValue item) { _Container.Add(Indexed.Create(_Index++, item)); }
public void Clear() { _Container.Clear();}
public bool Contains(TValue item) { return _Container.Contains(Indexed.Create(-1,item)); }
public void CopyTo(TValue[] array, int arrayIndex)
{
foreach (var value in this)
{
if (arrayIndex >= array.Length)
{
throw new ArgumentException("Not enough space in array");
}
array[arrayIndex] = value;
arrayIndex++;
}
}
public bool Remove(TValue item) { return _Container.Remove(Indexed.Create(-1, item)); }
public int Count {
get { return _Container.Count; }
}
public bool IsReadOnly {
get { return false; }
}
}
测试类
[Fact]
public void ShouldWorkWithSuperSortedSet()
{
// Sort points according to X
var set = new SuperSortedSet<Point2D>
(new System.Linq.Comparer<Point2D>((p0, p1) => p0.X.CompareTo(p1.X)));
set.Add(new Point2D(9,10));
set.Add(new Point2D(1,25));
set.Add(new Point2D(11,-10));
set.Add(new Point2D(2,99));
set.Add(new Point2D(5,55));
set.Add(new Point2D(5,23));
set.Add(new Point2D(11,11));
set.Add(new Point2D(21,12));
set.Add(new Point2D(-1,76));
set.Add(new Point2D(16,21));
var xs = set.Select(p=>p.X).ToList();
xs.Should().BeInAscendingOrder();
xs.Count.Should()
.Be(10);
xs.ShouldBeEquivalentTo(new[]{-1,1,2,5,5,9,11,11,16,21});
set.Remove(new Point2D(5,55));
xs = set.Select(p=>p.X).ToList();
xs.Count.Should()
.Be(9);
xs.ShouldBeEquivalentTo(new[]{-1,1,2,5,9,11,11,16,21});
set.Remove(new Point2D(5,23));
xs = set.Select(p=>p.X).ToList();
xs.Count.Should()
.Be(8);
xs.ShouldBeEquivalentTo(new[]{-1,1,2,9,11,11,16,21});
set.Contains(new Point2D(11, 11))
.Should()
.BeTrue();
set.Contains(new Point2D(-1, 76))
.Should().BeTrue();
// Note that the custom compartor function ignores the Y value
set.Contains(new Point2D(-1, 66))
.Should().BeTrue();
set.Contains(new Point2D(27, 66))
.Should().BeFalse();
}
标记结构
public struct Indexed<T>
{
public int Index { get; private set; }
public T Value { get; private set; }
public Indexed(int index, T value) : this()
{
Index = index;
Value = value;
}
public override string ToString()
{
return "(Indexed: " + Index + ", " + Value.ToString () + " )";
}
}
public class Indexed
{
public static Indexed<T> Create<T>(int indexed, T value)
{
return new Indexed<T>(indexed, value);
}
}
lambda comparer helper
public class Comparer<T> : IComparer<T>
{
private readonly Func<T, T, int> _comparer;
public Comparer(Func<T, T, int> comparer)
{
if (comparer == null)
throw new ArgumentNullException("comparer");
_comparer = comparer;
}
public int Compare(T x, T y)
{
return _comparer(x, y);
}
}
答案 7 :(得分:1)
您是否尝试过允许重复密钥的Lookup<TKey, TElement>
http://msdn.microsoft.com/en-us/library/bb460184.aspx
答案 8 :(得分:1)
这就是我解决问题的方式。它是线程安全的,尽管如果不需要,您可以简单地删除lock
。另外请注意,不支持在索引处使用任意Insert
,因为这可能会违反排序条件。
public class ConcurrentOrderedList<Titem, Tsort> : ICollection<Titem>
{
private object _lock = new object();
private SortedDictionary<Tsort, List<Titem>> _internalLists;
Func<Titem, Tsort> _getSortValue;
public ConcurrentOrderedList(Func<Titem,Tsort> getSortValue)
{
_getSortValue = getSortValue;
_internalLists = new SortedDictionary<Tsort, List<Titem>>();
}
public int Count { get; private set; }
public bool IsReadOnly => false;
public void Add(Titem item)
{
lock (_lock)
{
List<Titem> values;
Tsort sortVal = _getSortValue(item);
if (!_internalLists.TryGetValue(sortVal, out values))
{
values = new List<Titem>();
_internalLists.Add(sortVal, values);
}
values.Add(item);
Count++;
}
}
public bool Remove(Titem item)
{
lock (_lock)
{
List<Titem> values;
Tsort sortVal = _getSortValue(item);
if (!_internalLists.TryGetValue(sortVal, out values))
return false;
var removed = values.Remove(item);
if (removed)
Count--;
return removed;
}
}
public void Clear()
{
lock (_lock)
{
_internalLists.Clear();
}
}
public bool Contains(Titem item)
{
lock (_lock)
{
List<Titem> values;
Tsort sortVal = _getSortValue(item);
if (!_internalLists.TryGetValue(sortVal, out values))
return false;
return values.Contains(item);
}
}
public void CopyTo(Titem[] array, int arrayIndex)
{
int i = arrayIndex;
lock (_lock)
{
foreach (var list in _internalLists.Values)
{
list.CopyTo(array, i);
i += list.Count;
}
}
}
public IEnumerator<Titem> GetEnumerator()
{
foreach (var list in _internalLists.Values)
{
foreach (var item in list)
yield return item;
}
}
public int IndexOf(Titem item)
{
int i = 0;
var sortVal = _getSortValue(item);
lock (_lock)
{
foreach (var list in _internalLists)
{
if (object.Equals(list.Key, sortVal))
{
int intIndex = list.Value.IndexOf(item);
if (intIndex == -1)
return -1;
return i + intIndex;
}
i += list.Value.Count;
}
return -1;
}
}
public void Insert(int index, Titem item)
{
throw new NotSupportedException();
}
// Note this method is indeterminate if there are multiple
// items in the same sort position!
public void RemoveAt(int index)
{
int i = 0;
lock (_lock)
{
foreach (var list in _internalLists.Values)
{
if (i + list.Count < index)
{
i += list.Count;
continue;
}
else
{
list.RemoveAt(index - i);
return;
}
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
答案 9 :(得分:0)
问题在于你使用的东西不是一个关键的键(导致它出现多次)。
因此,如果你有真正的坐标,你应该把Point
作为你的SortedList的关键。
或者你创建一个List<List<Header>>
,你的第一个列表索引定义了x位置,内部列表索引了y位置(如果你愿意,反之亦然)。
答案 10 :(得分:0)
创建一个类并查询列表:
Public Class SortingAlgorithm
{
public int ID {get; set;}
public string name {get; set;}
public string address1 {get; set;}
public string city {get; set;}
public string state {get; set;}
public int age {get; set;}
}
//declare a sorting algorithm list
List<SortingAlgorithm> sortAlg = new List<SortingAlgorithm>();
//Add multiple values to the list
sortAlg.Add( new SortingAlgorithm() {ID = ID, name = name, address1 = address1, city = city, state = state, age = age});
sortAlg.Add( new SortingAlgorithm() {ID = ID, name = name, address1 = address1, city = city, state = state, age = age});
sortAlg.Add( new SortingAlgorithm() {ID = ID, name = name, address1 = address1, city = city, state = state, age = age});
//query and order by the list
var sortedlist = (from s in sortAlg
select new { s.ID, s.name, s.address1, s.city, s.state, s.age })
.OrderBy(r => r.ID)
.ThenBy(r=> r.name)
.ThenBy(r=> r.city)
.ThenBy(r=>r.state)
.ThenBy(r=>r.age);
答案 11 :(得分:0)
Linq.Lookup很酷,但是如果您的目标是简单地循环“键”,同时允许它们被复制,您可以使用此结构:
List<KeyValuePair<String, String>> FieldPatterns = new List<KeyValuePair<string, string>>() {
new KeyValuePair<String,String>("Address","CommonString"),
new KeyValuePair<String,String>("Username","UsernamePattern"),
new KeyValuePair<String,String>("Username","CommonString"),
};
然后你可以写:
foreach (KeyValuePair<String,String> item in FieldPatterns)
{
//use item.Key and item.Value
}
HTH
答案 12 :(得分:0)
对此的关键(双关语)是创建一个基于IComparable
的类来维护相等和散列,但如果不相等则永远不会比较为0。这可以完成,并且可以使用几个奖励创建 - 稳定排序(即,首先添加到排序列表中的值将保持其位置),ToString()
可以简单地返回实际的键字符串值。
这是一个应该做的技巧的结构键:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace System
{
/// <summary>
/// Defined in Totlsoft.Util.
/// A key that will always be unique but compares
/// primarily on the Key property, which is not required
/// to be unique.
/// </summary>
public struct StableKey : IComparable<StableKey>, IComparable
{
private static long s_Next;
private long m_Sequence;
private IComparable m_Key;
/// <summary>
/// Defined in Totlsoft.Util.
/// Constructs a StableKey with the given IComparable key.
/// </summary>
/// <param name="key"></param>
public StableKey( IComparable key )
{
if( null == key )
throw new ArgumentNullException( "key" );
m_Sequence = Interlocked.Increment( ref s_Next );
m_Key = key;
}
/// <summary>
/// Overridden. True only if internal sequence and the
/// Key are equal.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals( object obj )
{
if( !( obj is StableKey ) )
return false;
var dk = (StableKey)obj;
return m_Sequence.Equals( dk.m_Sequence ) &&
Key.Equals( dk.Key );
}
/// <summary>
/// Overridden. Gets the hash code of the internal
/// sequence and the Key.
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return m_Sequence.GetHashCode() ^ Key.GetHashCode();
}
/// <summary>
/// Overridden. Returns Key.ToString().
/// </summary>
/// <returns></returns>
public override string ToString()
{
return Key.ToString();
}
/// <summary>
/// The key that will be compared on.
/// </summary>
public IComparable Key
{
get
{
if( null == m_Key )
return 0;
return m_Key;
}
}
#region IComparable<StableKey> Members
/// <summary>
/// Compares this Key property to another. If they
/// are the same, compares the incremented value.
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public int CompareTo( StableKey other )
{
var cmp = Key.CompareTo( other.Key );
if( cmp == 0 )
cmp = m_Sequence.CompareTo( other.m_Sequence );
return cmp;
}
#endregion
#region IComparable Members
int IComparable.CompareTo( object obj )
{
return CompareTo( (StableKey)obj );
}
#endregion
}
}
答案 13 :(得分:0)
您可以使用SortedList,将您的值用于TKey,将int(count)用于TValue。
以下是一个示例:一个对单词的字母进行排序的函数。
private string sortLetters(string word)
{
var input = new System.Collections.Generic.SortedList<char, int>();
foreach (var c in word.ToCharArray())
{
if (input.ContainsKey(c))
input[c]++;
else
input.Add(c, 1);
}
var output = new StringBuilder();
foreach (var kvp in input)
{
output.Append(kvp.Key, kvp.Value);
}
string s;
return output.ToString();
}
答案 14 :(得分:0)
诀窍是使用唯一键扩充您的对象。参见以下通过的测试。我想要 保持我的点按X值排序。只需在我的比较函数中使用裸露的Point2D即可 导致具有相同X值的点被消除。所以我将Point2D包装在一个名为的标记类中 索引。
[Fact]
public void ShouldBeAbleToUseCustomComparatorWithSortedSet()
{
// Create comparer that compares on X value but when X
// X values are uses the index
var comparer = new
System.Linq.Comparer<Indexed<Point2D>>(( p0, p1 ) =>
{
var r = p0.Value.X.CompareTo(p1.Value.X);
return r == 0 ? p0.Index.CompareTo(p1.Index) : r;
});
// Sort points according to X
var set = new SortedSet<Indexed<Point2D>>(comparer);
int i=0;
// Create a helper function to wrap each point in a unique index
Action<Point2D> index = p =>
{
var ip = Indexed.Create(i++, p);
set.Add(ip);
};
index(new Point2D(9,10));
index(new Point2D(1,25));
index(new Point2D(11,-10));
index(new Point2D(2,99));
index(new Point2D(5,55));
index(new Point2D(5,23));
index(new Point2D(11,11));
index(new Point2D(21,12));
index(new Point2D(-1,76));
index(new Point2D(16,21));
set.Count.Should()
.Be(10);
var xs = set.Select(p=>p.Value.X).ToList();
xs.Should()
.BeInAscendingOrder();
xs.ShouldBeEquivalentTo(new[]{-1,1,2,5,5,9,11,11,16,21});
}
实现这项工作的实用工具
采用lambda的比较器
public class Comparer<T> : IComparer<T>
{
private readonly Func<T, T, int> _comparer;
public Comparer(Func<T, T, int> comparer)
{
if (comparer == null)
throw new ArgumentNullException("comparer");
_comparer = comparer;
}
public int Compare(T x, T y)
{
return _comparer(x, y);
}
}
标记结构
public struct Indexed<T>
{
public int Index { get; private set; }
public T Value { get; private set; }
public Indexed(int index, T value) : this()
{
Index = index;
Value = value;
}
public override string ToString()
{
return "(Indexed: " + Index + ", " + Value.ToString () + " )";
}
}
public class Indexed
{
public static Indexed<T> Create<T>(int indexed, T value)
{
return new Indexed<T>(indexed, value);
}
}
答案 15 :(得分:-1)
这是我的看法。请注意,这里可能是巨龙,对于我来说C#仍然很新。
用法:
SortedQueue<MyClass> queue = new SortedQueue<MyClass>();
// new list on key "0" is created and item added
queue.Enqueue(0, first);
// new list on key "1" is created and item added
queue.Enqueue(1, second);
// items is added into list on key "0"
queue.Enqueue(0, third);
// takes the first item from list with smallest key
MyClass myClass = queue.Dequeue();
class SortedQueue<T> {
public int Count;
public SortedList<int, List<T>> Queue;
public SortedQueue() {
Count = 0;
Queue = new SortedList<int, List<T>>();
}
public void Enqueue(int key, T value) {
List<T> values;
if (!Queue.TryGetValue(key, out values)){
values = new List<T>();
Queue.Add(key, values);
Count += 1;
}
values.Add(value);
}
public T Dequeue() {
if (Queue.Count > 0) {
List<T> smallest = Queue.Values[0];
if (smallest.Count > 0) {
T item = smallest[0];
smallest.Remove(item);
return item;
} else {
Queue.RemoveAt(0);
Count -= 1;
return Dequeue();
}
}
return default(T);
}
}