我希望在c#的文本文件中加入名字和姓氏,但只有一个内容包含15个名字和15个姓氏,如此,必须按字母顺序排列名字或姓氏< / p>
emily
adrian
camille
lim
ong
ang
如果第一个theт输出必须是名字
adrian ong
camille ang
emily lim
if last
Ang camille
lim emily
ong adrian
答案 0 :(得分:1)
以下提供了所需的输出,并允许您通过布尔标志控制名字或姓氏,您可以将其绑定到参数或某些输入。这是.NET小提琴:https://dotnetfiddle.net/bHuOWQ
using System;
using System.Linq; // Utilizing linq to perform sorting
using System.Collections.Generic; // Utilizing generic List to accumulate objects
// Statically provide sample data, but should use File.ReadAllLines when loading from file
string[] records = new string[] { //File.ReadAllLines to get from the file
"emily",
"adrian",
"camille",
"lim",
"ong",
"ang"
};
bool sortByFirstName = true; // Set to false if by last name
int range = records.Length / 2; // Since source data splits first and last names into same list, use value to define split between where first name stops and last name starts
var items = new List<string>(); // Define list to contain the sortable items
// Iterate through the first and last names to gather the sortable names
for (int i = 0; i < range; i++)
{
if (sortByFirstName == true) // If sorting by first name, format entry as "first last"
items.Add(string.Format("{0} {1}", records[i], records[i+range]));
else // Otherwise, sort by last name, format entry as "last first"
items.Add(string.Format("{1} {0}", records[i], records[i+range]));
}
var sortedItems = items.OrderBy(s => s); // Use Linq to perform sorting
foreach (var s in sortedItems)
Console.WriteLine(s); // Output the results
收率:
adrian ong
camille ang
emily lim