关于排序多维数组在C# [英] Regarding Sorting MultiDimensional Arrays in C#
问题描述
我试图找出一种方法来正确地排序一堆不同的数组列表。
我发布内容文章,并且数组列表中的每个值[0]将与每个其他值[0]相关。等等。每个元素组成完整内容项的集合部分。
I am trying to figure out a way to correctly sort a bunch of different arraylists. I am publishing content articles and every value [0] in an arraylist will relate to every other value [0]. and so on. Each element makes up the collective parts of a complete content item.
现在,最后一个元素,即热门程度,是项目收到的点击量。
Now, the last element, popularity, is the amount of clicks an item has received. How do I do a sort of the content items based on popularity without mixing up the html for each article?
* 编辑
*EDIT I am limited by the .NET 2.0 Framework at Work*
下面是代码...感谢。
Below is the code... thanks.
public class MultiDimDictList : Dictionary<string, ArrayList> { }
myDicList.Add("fly", a_fly);
myDicList.Add("img", a_img);
myDicList.Add("bar", a_bar);
myDicList.Add("meter", a_meter);
myDicList.Add("block", a_block);
myDicList.Add("popularity", a_pop);
推荐答案
如果使用以下代码,使用Linq OrderBy
If you use the following code you can convert your existing dictionary of arraylists into a collection of Dictionaries and thus allowing a simple sort using Linq OrderBy
// Get the shortest arraylist length (they should be equal this is just a paranoia check!)
var count=myDicList.Values.Min(x=>x.Count);
// Get the collection of Keys
var keys=myDicList.Keys;
// Perform the conversion
var result=Enumerable.Range(0,count).Select(i=>keys.Select(k=>new {Key=k,Value=myDicList[k][i]}).ToDictionary(x=>x.Key,x=>x.Value));
var sorted=result.OrderByDescending(x=>x["popularity"]).ToList()
- 编辑.NET 2.0版本
-- EDIT VERSION FOR .NET 2.0
首先需要一个比较器类
class PopularityComparison : IComparer<Dictionary<string,object>> {
private bool _sortAscending;
public PopularityComparison(bool sortAscending) {
_sortAscending = sortAscending;
}
public int Compare(Dictionary<string, object> x, Dictionary<string, object> y) {
object xValue = x["popularity"];
object yValue = y["popularity"];
// Sort Ascending
if (_sortAscending) {
return Comparer.Default.Compare(xValue, yValue);
} else {
return Comparer.Default.Compare(yValue, xValue);
}
}
}
可以使用以下代码
// Get the shortest arraylist length (they should be equal this is just a paranoia check!)
// Replacement for min
int count = int.MaxValue;
foreach (ArrayList a in myDicList.Values) if (a.Count < count) count = a.Count;
// Get the collection of Keys
Dictionary<string, ArrayList>.KeyCollection keys = myDicList.Keys;
// Perform the conversion
List<Dictionary<string, object>> result = new List<Dictionary<string, object>>(count);
for (int i = 0; i < count; i++) {
Dictionary<string, object> row = new Dictionary<string, object>(keys.Count);
foreach (string key in keys) row.Add(key, myDicList[key][i]);
result.Add(row);
}
然后最终按人气升序顺序排序
And then finally to sort in ascending popularity order
result.Sort(new PopularityComparison(true));
或降序
result.Sort(new PopularityComparison(true));
这篇关于关于排序多维数组在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!