我想知道是否有任何方法可以使用LINQ对这段数据进行排序:
Firstname lastname age
Xxxxxxxxx xxxxxxxxx xxxx
Xxxxxxxxx xxxxxxxxx xxxx
* group YYYY <---- contained at firstName column
Xxxxxxxxx xxxxxxxxx xxxx
Xxxxxxxxx xxxxxxxxx xxxx
* group BBB
Xxxxxxxxx xxxxxxxxx xxxx
Xxxxxxxxx xxxxxxxxx xxxx
* group LLL
要:
Group Firstname lastname age
YYYY Xxxxxxxxx xxxxxxxxx xxxx
YYYY xxxxxxxxx xxxxxxxxx xxxx
BBB Xxxxxxxxx xxxxxxxxx xxxx
BBB Xxxxxxxxx xxxxxxxxx xxxx
LLL Xxxxxxxxx xxxxxxxxx xxxx
LLL xxxxxxxxx xxxxxxxxx xxxx
我已经使用For语句,从列表末尾开始获取组名然后将该值存储在局部变量中并继续使用“group name”
填充组列然后使用LINQ来选择FirstName
列不包含*
的所有位置。
有什么想法吗?
答案 0 :(得分:2)
您可以使用聚合:
执行此操作public static void Main()
{
var data = new MyClass[]
{
new MyClass{FirstName="Tom"},
new MyClass{FirstName="Dick"},
new MyClass{FirstName="Harry"},
new MyClass{FirstName="* group YYYY"},
new MyClass{FirstName="Matthew"},
new MyClass{FirstName="Mark"},
new MyClass{FirstName="Luke"},
new MyClass{FirstName="John"},
new MyClass{FirstName="* group BBB"},
new MyClass{FirstName="Moe"},
new MyClass{FirstName="Larry"},
new MyClass{FirstName="Curly"},
new MyClass{FirstName="* group LLL"},
};
var groups = new Dictionary<string, List<MyClass>>();
data.Aggregate(new List<MyClass>(), (a, b) =>
{
if (b.FirstName.StartsWith("* group "))
{
groups[b.FirstName.Substring(8)] = a;
return new List<MyClass>();
}
a.Add(b);
return a;
});
foreach (var group in groups.Keys)
foreach (var record in groups[group])
Console.WriteLine("{0} {1}", group, record.FirstName);
}
public class MyClass
{
public string FirstName { get; set; }
}
输出:
YYYY Tom
YYYY Dick
YYYY Harry
BBB Matthew
BBB Mark
BBB Luke
BBB John
LLL Moe
LLL Larry
LLL Curly