本文整理汇总了C#中Common.List.Sort方法的典型用法代码示例。如果您正苦于以下问题:C# List.Sort方法的具体用法?C# List.Sort怎么用?C# List.Sort使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Common.List
的用法示例。
在下文中一共展示了List.Sort方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: load
public List<string> load(string file)
{
List<string> ldts = new List<string>();
try
{
archive = fileUtil.load(file);
}
catch (Exception e)
{
handleException(e);
}
List<DateTime> ldt = new List<DateTime>(archive.Keys);
if (ldt.Count > 0)
{
mapTime = new Dictionary<string, DateTime>();
ldt.Sort();
foreach (DateTime dt in ldt)
{
string dts = partDateTime(dt);
if (!mapTime.ContainsKey(dts))
{
mapTime.Add(dts, dt);
ldts.Add(dts);
}
}
}
return ldts;
}
示例2: Main
static void Main(string[] args)
{
PrimeCalculator calc = new PrimeCalculator();
calc.GetAllPrimes(10000);
for (int n = 1000; n < 10000; n++)
{
int d1 = n % 10;
int d2 = (n / 10) % 10;
int d3 = (n / 100) % 10;
int d4 = n / 1000;
var permutations = Permutator.Permutate(new int[] {d1, d2, d3, d4}.ToList());
var numbers = new List<int>();
foreach (var perm in permutations)
{
var num = perm[0] + perm[1] * 10 + perm[2] * 100 + perm[3] * 1000;
if (calc.IsPrime((ulong)num) && !numbers.Contains(num) && num>999 && num>=n)
numbers.Add(num);
}
numbers.Sort();
for (int i = 1; i < numbers.Count-1; i++)
{
for (int j = i+1; j < numbers.Count; j++)
{
if (numbers[j]-numbers[i]==numbers[i]-numbers[0])
Console.Write("{0}{1}{2}\n", numbers[0], numbers[i], numbers[j]);
}
}
}
}
示例3: Main
static void Main(string[] args)
{
int totalCount = 3;
List<Student> listStudent = new List<Student>();
for (int i = 0; i < 3; i++)
{
Student objStudent = new Student();
Console.Write("Please enter the Student ID: ");
objStudent.StudentId = Int32.Parse(Console.ReadLine());
Console.Write("Please enter the Student Name: ");
objStudent.Name = Console.ReadLine();
listStudent.Add(objStudent);
}
//Query to get by name - only first occurence
//Student student = listStudent.First(x => x.Name == "Karthik");
Student student = listStudent.FirstOrDefault(x => x.Name == "Karthik");
if(student != null)
Console.WriteLine(string.Format("ID: {0} Name: {1}", student.StudentId, student.Name));
//Query to get by name - all occurences
//IEnumerable<Student> stdList = listStudent.Where(x => x.Name == "Karthik");
IEnumerable<Student> stdList = listStudent.Where(x => x.StudentId >= 20);
foreach (var student1 in stdList)
{
Console.WriteLine(string.Format("ID: {0} Name: {1}", student1.StudentId, student1.Name));
}
listStudent.Sort((std1, std2) => std1.Name.CompareTo(std2.Name));
listStudent.ForEach(x=>Console.WriteLine(x.Name));
}
示例4: InvestMoney
public void InvestMoney()
{
int numberOfInvestments = numberOfMembers;
//The index doing the investing:
for(int i=0 ;i < numberOfMembers; i++){
var investor = this.Members[i];
List<double> partitions = new List<double>();
//Generate N random numbers
for (int j = 0; j < numberOfInvestments -1 ; j++) {
partitions.Add(rand.NextDouble());
}
partitions.Add(1);
//Sort the numbers
partitions.Sort();
//Each partition corresponds to the investment amount in order
//The index getting the investment
double totalPercentInvested = 0;
double totalMoneyInvested = 0;
for (int j = 0; j < numberOfInvestments; j++) {
double percentToInvest = (partitions[j] - totalPercentInvested);
var investee = this.Members[j];
investee.TakeInvestment(investor, percentToInvest * investor.GetAssets());
totalMoneyInvested += percentToInvest * investor.GetAssets() ;
totalPercentInvested += percentToInvest;
}
//Debug.Print("Total percent invested: " + totalPercentInvested.ToString());
//Debug.Print("Total monies invested: " + totalMoneyInvested.ToString());
}
}
示例5: LoadDefines
/// <summary>
/// 从外部文件中获取Options列表
/// </summary>
public static CTreeNode LoadDefines()
{
List<ConfigurationFileOption.Define> Definelist = new List<ConfigurationFileOption.Define>();
Definelist = Utility.LoadObjFromXml<List<ConfigurationFileOption.Define>>(DefineFilename);
Definelist.Sort((x, y) => { return x.Path.CompareTo(y.Path); });
//Root Node
var Root = new CTreeNode(string.Empty);
foreach (var item in Definelist)
{
System.Diagnostics.Debug.WriteLine(item.Path);
CTreeNode.AddToRootNode(Root, item.Path);
ConfigurationItemDictionary.Add(item.Path, item);
}
return Root;
}
示例6: NumberThatOccurOddNumberOfTimes
private static void NumberThatOccurOddNumberOfTimes(List<int> numbers)
{
var num = new List<int>(numbers);
num.Sort();
int previousNumber = num[0];
int currentNumber = 0;
var numberOfOcc = 1;
var oddNumbers = new List<int>();
for (int i = 1; i < num.Count; i++)
{
currentNumber = num[i];
if (currentNumber == previousNumber)
{
numberOfOcc++;
}
else
{
if (numberOfOcc % 2 == 0)
{
for (int x = 0; x < numberOfOcc; x++)
{
oddNumbers.Add(previousNumber);
}
}
numberOfOcc = 1;
}
previousNumber = currentNumber;
}
if (numberOfOcc % 2 == 0)
{
for (int x = 0; x < numberOfOcc; x++)
{
oddNumbers.Add(previousNumber);
}
}
Console.WriteLine("Numbers that occur odd times ");
foreach (var oddNumber in oddNumbers)
{
Console.WriteLine("{0} ", oddNumber);
}
}
示例7: CreateFile
/// <summary>
/// 生成YAML文件
/// </summary>
/// <param name="fileName"></param>
/// <param name="Items"></param>
public static void CreateFile(string fileName, List<string> Items)
{
//假定Items的格式为Path:Value
//Value为字符串(可以带有双引号)
StreamWriter YamlDoc = new StreamWriter(fileName, false, Encoding.UTF8);
Items.Sort((x, y) => { return x.CompareTo(y); });
for (int i = 0; i < Items.Count; i++)
{
if (i == 0)
{
//第一个项目
PrintYaml(YamlDoc, 0, Items[i]);
continue;
}
//从后一个字符串
var Last = Items[i].Split(".".ToCharArray());
var Pre = Items[i - 1].Split(".".ToCharArray());
//表示相同段数
int SameSegment = 0;
for (int j = 0; j < Math.Min(Last.Length, Pre.Length); j++)
{
if (Last[j] != Pre[j])
{
SameSegment = j;
break;
}
}
//Items[i]去掉相同的字符首
string RemovedItems = string.Empty;
for (int k = SameSegment; k < Last.Length; k++)
{
if (k!= Last.Length - 1)
{
RemovedItems += Last[k] + ".";
}
else
{
RemovedItems += Last[k];
}
}
PrintYaml(YamlDoc, SameSegment, RemovedItems);
}
YamlDoc.Close();
}
示例8: CreateFile
/// <summary>
/// 生成YAML文件
/// </summary>
/// <param name="fileName"></param>
/// <param name="items"></param>
public static void CreateFile(string fileName, List<string> items)
{
//假定Items的格式为Path:Value
//Value为字符串(可以带有双引号)
var yamlDoc = new StreamWriter(fileName, false, Encoding.UTF8);
items.Sort((x, y) => string.Compare(x, y, StringComparison.Ordinal));
for (var i = 0; i < items.Count; i++)
{
if (i == 0)
{
//第一个项目
PrintYaml(yamlDoc, 0, items[i]);
continue;
}
//从后一个字符串
var last = items[i].Split(".".ToCharArray());
var pre = items[i - 1].Split(".".ToCharArray());
//表示相同段数
var sameSegment = 0;
for (var j = 0; j < Math.Min(last.Length, pre.Length); j++)
{
if (last[j] != pre[j])
{
sameSegment = j;
break;
}
}
//Items[i]去掉相同的字符首
var removedItems = string.Empty;
for (var k = sameSegment; k < last.Length; k++)
{
if (k != last.Length - 1)
{
removedItems += last[k] + ".";
}
else
{
removedItems += last[k];
}
}
PrintYaml(yamlDoc, sameSegment, removedItems);
}
yamlDoc.Close();
}
示例9: Load
public List<RouteInstance> Load(int delivery_id)
{
// check values
if (delivery_id == 0)
throw new ArgumentException("Delivery_id cannot be zero", "delivery_id");
var list = new List<RouteInstance>();
object[] rows;
lock (Database.Instance)
{
var sql = SQLQueryBuilder.SelectFieldsWhereFieldEquals(TABLE_NAME, "delivery_id", delivery_id.ToString(), new[] { "route_id", "departure_time" });
rows = Database.Instance.FetchRows(sql);
}
foreach (object[] row in rows)
{
int route_id = row[0].ToInt();
DateTime departureTime = (DateTime)row[1];
Route route = routeDataHelper.Load(route_id, true);
list.Add(new RouteInstance(route, departureTime));
}
list.Sort();
return list;
}
示例10: GetRepositories
protected IList<GithubRepository> GetRepositories()
{
List<GithubRepository> repositories = null;
InvokeInGithubOperationContext(() => { repositories = PSCmdlet.GithubChannel.GetRepositories(); });
List<GithubOrganization> organizations = null;
InvokeInGithubOperationContext(() => { organizations = PSCmdlet.GithubChannel.GetOrganizations(); });
List<GithubRepository> orgRepositories = new List<GithubRepository>();
foreach (var organization in organizations)
{
List<GithubRepository> currentOrgRepositories = null;
InvokeInGithubOperationContext(() => { currentOrgRepositories = PSCmdlet.GithubChannel.GetRepositoriesFromOrg(organization.Login); });
orgRepositories.AddRange(currentOrgRepositories);
}
repositories.Sort();
orgRepositories.Sort();
repositories.AddRange(orgRepositories);
return repositories.Where(r => r.Private == false).ToList();
}
示例11: GetRouterTable
public static string GetRouterTable()
{
// The number of bytes needed.
int bytesNeeded = 0;
// The result from the API call.
int result = GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false);
// Call the function, expecting an insufficient buffer.
if (result != ErrorInsufficientBuffer)
{
// Throw an exception.
throw new Win32Exception(result);
}
// Allocate the memory, do it in a try/finally block, to ensure
// that it is released.
IntPtr buffer = IntPtr.Zero;
// Try/finally.
try
{
// Allocate the memory.
buffer = Marshal.AllocCoTaskMem(bytesNeeded);
// Make the call again. If it did not succeed, then
// raise an error.
result = GetIpNetTable(buffer, ref bytesNeeded, false);
// If the result is not 0 (no error), then throw an exception.
if (result != 0)
{
// Throw an exception.
throw new Win32Exception(result);
}
// Now we have the buffer, we have to marshal it. We can read
// the first 4 bytes to get the length of the buffer.
int entries = Marshal.ReadInt32(buffer);
// Increment the memory pointer by the size of the int.
IntPtr currentBuffer = new IntPtr(buffer.ToInt64() +
Marshal.SizeOf(typeof(int)));
// Allocate an array of entries.
MibIpnetrow[] table = new MibIpnetrow[entries];
// Cycle through the entries.
for (int index = 0; index < entries; index++)
{
// Call PtrToStructure, getting the structure information.
table[index] = (MibIpnetrow)Marshal.PtrToStructure(new
IntPtr(currentBuffer.ToInt64() + (index *
Marshal.SizeOf(typeof(MibIpnetrow)))), typeof(MibIpnetrow));
}
List<string> strtable = new List<string>();
for (int index = 0; index < entries; index++)
{
MibIpnetrow row = table[index];
IPAddress ip = new IPAddress(BitConverter.GetBytes(row.dwAddr));
StringBuilder sbMac = new StringBuilder();
sbMac.Append(row.mac0.ToString("X2") + '-');
sbMac.Append(row.mac1.ToString("X2") + '-');
sbMac.Append(row.mac2.ToString("X2") + '-');
sbMac.Append(row.mac3.ToString("X2") + '-');
sbMac.Append(row.mac4.ToString("X2") + '-');
sbMac.AppendLine(row.mac5.ToString("X2"));
strtable.Add(string.Format("IP: {0}\t\t\tMac: {1}", ip, sbMac));
}
string str = "";
strtable.Sort();
strtable.ForEach(m => str += m);
return str;
}
finally
{
// Release the memory.
FreeMibTable(buffer);
}
}
示例12: GetCandidates
public static IEnumerable<Candidate> GetCandidates(
ExplorationSpace space,
ExplorationNode start,
ExplorationNode lastGoal,
HashSet<uint> busyObjects,
Scorer scorer,
int numRecommendations,
bool descending)
{
if (busyObjects == null)
busyObjects = new HashSet<uint>();
List<Candidate> candidates = new List<Candidate>();
foreach (ExplorationNode node in space.Nodes)
{
if (start == node)
continue;
// Make sure it's reachable
ExplorationEdge[] path = start.GetPathOut(node.Id);
if (path != null)
{
// Add it as a candidate if the score is high enough
double score = scorer(start, node);
ExplorationEdge edge = path[0];
ExplorationNode goal = path.Last().Target;
double sentimentScore = SentimentScore(score, path);
candidates.Add(new Candidate(path, goal, sentimentScore));
}
}
// Sort the candidates by score
candidates.Sort((c1, c2) => c1.Score.CompareTo(c2.Score));
if (descending == true)
candidates.Reverse();
// Add the previous goal to the front if we still have a path to it
if (lastGoal != null)
{
ExplorationEdge[] oldPath = start.GetPathOut(lastGoal.Id);
if (oldPath != null)
candidates.Insert(0, new Candidate(oldPath, lastGoal, 0.0));
}
HashSet<ExplorationNode> seenGoals = new HashSet<ExplorationNode>();
HashSet<ExplorationEdge> seenEdges = new HashSet<ExplorationEdge>();
// Pick the top N
int count = 0;
foreach (Candidate candidate in candidates)
{
ExplorationNode goal = candidate.Goal;
if (candidate.Path.Length == 0)
continue;
ExplorationEdge edge = candidate.Path[0];
// Nix this event if it uses an object that's currently in use
// TODO: Assumes only one event per edge
TransitionEvent evt = edge.Events[0];
foreach (uint id in evt.Participants)
if (busyObjects.Contains(id) == true)
goto skipCandidate;
// If this is a novel direction to go, add it
bool seenGoal = seenGoals.Contains(goal);
bool seenEdge = seenEdges.Contains(edge);
if (seenGoal == false && seenEdge == false)
{
seenGoals.Add(goal);
seenEdges.Add(edge);
count++;
yield return candidate;
}
if (count >= numRecommendations)
break;
skipCandidate : continue;
}
}
示例13: Load
public List<WeeklyTime> Load(int route_id)
{
// check values
if (route_id == 0)
throw new ArgumentException("Route_id cannot be zero", "route_id");
var list = new List<WeeklyTime>();
lock (Database.Instance)
{
var sql = SQLQueryBuilder.SelectFieldsWhereFieldEquals(TABLE_NAME, "route_id", route_id.ToString(), new[]{ID_COL_NAME, "weekly_time"});
var rows = Database.Instance.FetchRows(sql);
foreach (object[] row in rows)
{
int id = row[0].ToInt();
long ticks = (long)row[1];
list.Add(new WeeklyTime(ticks) { ID = id});
}
}
list.Sort();
return list;
}
示例14: SortMail
private List<BsonDocument> SortMail(List<BsonDocument> MailList, BsonDocument Search)
{
List<BsonDocument> MailNikeName = nnm.GetAllData();
List<BsonDocument> MailIp = im.GetAllData();
List<BsonDocument> MailAddress = mam.GetAllData();
List<BsonDocument> MailPhone = pm.GetAllData();
List<BsonDocument> MailContainer = cm.GetAllData();
foreach (BsonDocument Mail in MailList)
{
int Weights = 0;
if (Mail.Contains("MailFrom"))
{
foreach (BsonValue MailFrom in Mail.GetValue("MailFrom").AsBsonArray)
{
if (!MailFrom.AsBsonArray[0].IsBsonNull)
{
Weights += MailNikeName.Find((x) => x.GetValue("_id").AsObjectId == MailFrom.AsBsonArray[0].AsObjectId).GetValue("RepeatTimes").AsInt32;
}
if (!MailFrom.AsBsonArray[1].IsBsonNull)
{
Weights += MailAddress.Find((x) => x.GetValue("_id").AsObjectId == MailFrom.AsBsonArray[1].AsObjectId).GetValue("RepeatTimes").AsInt32;
}
}
}
if (Mail.Contains("MailTO"))
{
foreach (BsonValue MailTO in Mail.GetValue("MailTO").AsBsonArray)
{
if (!MailTO.AsBsonArray[0].IsBsonNull)
{
Weights += MailNikeName.Find((x) => x.GetValue("_id").AsObjectId == MailTO.AsBsonArray[0].AsObjectId).GetValue("RepeatTimes").AsInt32;
}
if (!MailTO.AsBsonArray[1].IsBsonNull)
{
Weights += MailAddress.Find((x) => x.GetValue("_id").AsObjectId == MailTO.AsBsonArray[1].AsObjectId).GetValue("RepeatTimes").AsInt32;
}
}
}
if (Mail.Contains("MailCC"))
{
foreach (BsonValue MailCC in Mail.GetValue("MailCC").AsBsonArray)
{
if (!MailCC.AsBsonArray[0].IsBsonNull)
{
Weights += MailNikeName.Find((x) => x.GetValue("_id").AsObjectId == MailCC.AsBsonArray[0].AsObjectId).GetValue("RepeatTimes").AsInt32;
}
if (!MailCC.AsBsonArray[1].IsBsonNull)
{
Weights += MailAddress.Find((x) => x.GetValue("_id").AsObjectId == MailCC.AsBsonArray[1].AsObjectId).GetValue("RepeatTimes").AsInt32;
}
}
}
if (Mail.Contains("MailBCC"))
{
foreach (BsonValue MailBCC in Mail.GetValue("MailBCC").AsBsonArray)
{
if (!MailBCC.AsBsonArray[0].IsBsonNull)
{
Weights += MailAddress.Find((x) => x.GetValue("_id").AsObjectId == MailBCC.AsBsonArray[0].AsObjectId).GetValue("RepeatTimes").AsInt32;
}
if (!MailBCC.AsBsonArray[1].IsBsonNull)
{
Weights += MailAddress.Find((x) => x.GetValue("_id").AsObjectId == MailBCC.AsBsonArray[1].AsObjectId).GetValue("RepeatTimes").AsInt32;
}
}
}
for (int i = 0; i < Mail.GetValue("HTMLBodyIps").AsBsonArray.Count; i += 2)
{
Weights += MailIp.Find((x) => x.GetValue("Ip") == Mail.GetValue("HTMLBodyIps").AsBsonArray[i].AsString).GetValue("RepeatTimes").AsInt32 * Mail.GetValue("HTMLBodyIps").AsBsonArray[i + 1].AsInt32;
}
for (int i = 0; i < Mail.GetValue("HTMLBodyMailAddress").AsBsonArray.Count; i += 2)
{
Weights += MailAddress.Find((x) => x.GetValue("Address").AsString == Mail.GetValue("HTMLBodyMailAddress").AsBsonArray[i].AsString).GetValue("RepeatTimes").AsInt32 * Mail.GetValue("HTMLBodyMailAddress").AsBsonArray[i + 1].AsInt32;
}
for (int i = 0; i < Mail.GetValue("HTMLBodyPhone").AsBsonArray.Count; i += 2)
{
Weights += MailPhone.Find((x) => x.GetValue("Phone") == Mail.GetValue("HTMLBodyPhone").AsBsonArray[i].AsString).GetValue("RepeatTimes").AsInt32 * Mail.GetValue("HTMLBodyPhone").AsBsonArray[i + 1].AsInt32;
}
for (int i = 0; i < Mail.GetValue("HTMLBodyContainer").AsBsonArray.Count; i += 2)
{
Weights += MailContainer.Find((x) => x.GetValue("Container") == Mail.GetValue("HTMLBodyContainer").AsBsonArray[i].AsString).GetValue("RepeatTimes").AsInt32 * Mail.GetValue("HTMLBodyContainer").AsBsonArray[i + 1].AsInt32;
}
for (int i = 0; i < Mail.GetValue("TextBodyIps").AsBsonArray.Count; i += 2)
{
Weights += MailIp.Find((x) => x.GetValue("Ip") == Mail.GetValue("TextBodyIps").AsBsonArray[i].AsString).GetValue("RepeatTimes").AsInt32 * Mail.GetValue("TextBodyIps").AsBsonArray[i + 1].AsInt32;
}
for (int i = 0; i < Mail.GetValue("TextBodyMailAddress").AsBsonArray.Count; i += 2)
{
Weights += MailAddress.Find((x) => x.GetValue("Address").AsString == Mail.GetValue("TextBodyMailAddress").AsBsonArray[i].AsString).GetValue("RepeatTimes").AsInt32 * Mail.GetValue("TextBodyMailAddress").AsBsonArray[i + 1].AsInt32;
}
for (int i = 0; i < Mail.GetValue("TextBodyPhone").AsBsonArray.Count; i += 2)
{
Weights += MailPhone.Find((x) => x.GetValue("Phone") == Mail.GetValue("TextBodyPhone").AsBsonArray[i].AsString).GetValue("RepeatTimes").AsInt32 * Mail.GetValue("TextBodyPhone").AsBsonArray[i + 1].AsInt32;
}
for (int i = 0; i < Mail.GetValue("TextBodyContainer").AsBsonArray.Count; i += 2)
{
Weights += MailContainer.Find((x) => x.GetValue("Container") == Mail.GetValue("TextBodyContainer").AsBsonArray[i].AsString).GetValue("RepeatTimes").AsInt32 * Mail.GetValue("TextBodyContainer").AsBsonArray[i + 1].AsInt32;
}
Mail.Add("Weights", Weights);
}
//.........这里部分代码省略.........
示例15: ProcessAnimation
/// <summary>
/// Converts an intermediate format content pipeline AnimationContent
/// object to our runtime AnimationClip format.
/// </summary>
static AnimationClip ProcessAnimation(AnimationContent animation,
Dictionary<string, int> boneMap)
{
List<Keyframe> keyframes = new List<Keyframe>();
// For each input animation channel.
foreach (KeyValuePair<string, AnimationChannel> channel in
animation.Channels)
{
// Look up what bone this channel is controlling.
int boneIndex;
if (!boneMap.TryGetValue(channel.Key, out boneIndex))
{
throw new InvalidContentException(string.Format(
"Found animation for bone '{0}', " +
"which is not part of the skeleton.", channel.Key));
}
// Convert the keyframe data.
foreach (AnimationKeyframe keyframe in channel.Value)
{
keyframes.Add(new Keyframe(boneIndex, keyframe.Time,
keyframe.Transform));
}
}
// Sort the merged keyframes by time.
keyframes.Sort(CompareKeyframeTimes);
if (keyframes.Count == 0)
throw new InvalidContentException("Animation has no keyframes.");
if (animation.Duration <= TimeSpan.Zero)
throw new InvalidContentException("Animation has a zero duration.");
return new AnimationClip(animation.Duration, keyframes);
}