C# 按 int 排序列表,但如果找到重复的值,则按另一个 int 排序

  • 本文关键字:int 排序 另一个 如果 列表 c#
  • 更新时间 :
  • 英文 :


我正在使用包含自定义类的 C# 列表。类看起来像这样;

public class GeneratorLine
{
public string TextString { get; set; }
public int DatabaseId { get; set; }
public int LineNumber { get; set; }
public int Rank { get; set; }
}

现在,我想将"TextString"打印到.txt文件中,行号应该是行在文件中放置位置的主控制器。但是,可能会出现行号的重复值,在这种情况下,应按"DatabaseId"对它们进行分组,并按此顺序放置在文件中。如果"Rank"中存在一个值,则应按此排序。

我尝试过使用GroupBy,OrderBy等的不同组合,但我的主要问题是相同的"DatabaseId"可以具有低"行号"和高"行号",而不同的"DatabaseId"可以在它们之间具有"行号"。

Example of file output:
Text1 (DatabaseId: 1, Linenumber: 1, Rank: null)
Text2 (DatabaseId: 1, Linenumber: 2, Rank: null)
Text3 (DatabaseId: 1, Linenumber: 3, Rank: null)
Text4 (DatabaseId: 3, Linenumber: 4, Rank: 1)
Text5 (DatabaseId: 3, Linenumber: 5, Rank: 1)
Text6 (DatabaseId: 3, Linenumber: 6, Rank: 1)
Text7 (DatabaseId: 2, Linenumber: 4, Rank: 2)
Text8 (DatabaseId: 2, Linenumber: 5, Rank: 2)
Text9 (DatabaseId: 2, Linenumber: 6, Rank: 2)
Text10 (DatabaseId: 1, Linenumber: 7, Rank: null)

任何帮助都非常感谢。

您可以在类中实现接口IComparable,例如

public class GeneratorLine : IComparable
{
public string TextString { get; set; }
public int DatabaseId { get; set; }
public int LineNumber { get; set; }
public int? Rank { get; set; } // If Rank can be null, its type should be int?
public int CompareTo(object obj)
{
if (obj == null) return 1;
GeneratorLine otherLine = obj as GeneratorLine;
if (otherLine != null)
{
// Set by default the comparison between ranks to 0 (meaning they are equals)
int RankComparison = 0;
// If both ranks are not null, let's compare them
if (Rank != null && otherLine.Rank != null)
RankComparison = (int)this.Rank?.CompareTo(otherLine.Rank);
// If both ranks are equals or null
if (RankComparison == 0)
{
// compare by LineNumber
int LineNumberComparison = this.LineNumber.CompareTo(otherLine.LineNumber);
// if they have same LineNumber
if (LineNumberComparison == 0)
{
// compare them by DatabaseId
return this.DatabaseId.CompareTo(otherLine.DatabaseId);
}
// else compare them by LineNumber
return LineNumberComparison;
}
// If both ranks are not null and differents, return their comparison
return RankComparison;
}
else
throw new ArgumentException("Object is not a GeneratorLine");
}
}

然后,在您的代码中,只需使用 :

YourCollection.Sort();

YourCollection在哪里是你的List<GeneratorLine>

自己尝试一下

最新更新