我试图按流行度评价一些Gin's,我在Gin列表中读取文本文件,每个Gin以0的流行度开始,但是当我对列表进行排序时,它会混合出来,而不是以原始的字母顺序排列如果没有排序则按顺序排列。
没有排序 -
这是我正在使用的代码 -
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class GinListClass : MonoBehaviour
{
[Header("the text file holding Gin's, Country, ABV and the Price")]
public TextAsset ginTextFile;
[Header("the Lists, public for debugging")]
public List< string > ginString = new List< string >();
private int rating;
private int linesInFileCount;
void Start ()
{
rating = 0;
List<GinList> gins = new List<GinList>();
string[] linesInFile = ginTextFile.text.Split('\n');
foreach (string line in linesInFile)
{
linesInFileCount++;
ginString.Add(line);
}
for (var i = 0; i < linesInFileCount; i++)
{
gins.Add( new GinList(ginString[i], ginString[i+1], ginString[i+2], ginString[i+3], rating+Random.Range(0,100)));
i+=4;
}
gins.Sort();
//gins.Reverse();
Debug.Log("A .. Gin count is " + gins.Count);
foreach(GinList gin in gins)
{
Debug.Log(gin._ginName + " - " + gin._country + " - " + gin._abv + " - " + gin._price + " - " + gin._pop);
}
gins.Clear();
}
}
和 -
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class GinListClass : MonoBehaviour
{
[Header("the text file holding Gin's, Country, ABV and the Price")]
public TextAsset ginTextFile;
[Header("the Lists, public for debugging")]
public List< string > ginString = new List< string >();
private int linesInFileCount;
void Start ()
{
List<GinList> gins = new List<GinList>();
string[] linesInFile = ginTextFile.text.Split('\n');
foreach (string line in linesInFile)
{
linesInFileCount++;
ginString.Add(line);
}
for (var i = 0; i < linesInFileCount; i++)
{
gins.Add( new GinList(ginString[i], ginString[i+1], ginString[i+2], ginString[i+3], Random.Range(0,100)));
i+=4;
}
//gins.Sort();
//gins.Reverse();
Debug.Log("A .. Gin count is " + gins.Count);
foreach(GinList gin in gins)
{
Debug.Log(gin._ginName + " - " + gin._country + " - " + gin._abv + " - " + gin._price + " - " + gin._pop);
}
gins.Clear();
}
}
如果我给予Gin评级他们排序正确。
有人请求我指出正确的方向,谢谢你。
答案 0 :(得分:2)
某些排序算法是稳定的,有些则不是。可能,该库使用的排序算法不稳定,即它可能会重新排序比较均等的项目。
作为一种解决方案,您可以先按受欢迎程度订购,但如果它们具有相同的受欢迎程度,则按名称排序。我不知道C#(或者你正在使用的任何东西),但它应该像这个伪代码
int compare(const myobject & i1, const myobject & i2) {
if(compare(i1.popularity, i2.popularity) == 0) {
// reverse sort by popularity
return -compare(i1.popularity, i2.popularity);
}
return compare(i1.name, i2.set2id);
}
将其用作
gins.Sort(compare);
编辑:解决方案