我有像Avinash_Create.sql,Avinash_Insert.sql,Avinash_Update.sql,Avinash_Delete.sql等文件。
我需要遍历文件列表,并根据名称和顺序通过创建,插入,更新和删除文件对它们进行分组。
我发现很难完成。这就是我到目前为止所做的:
var userGroups = shortfilenames.GroupBy(s => s.Substring(0, s.IndexOf('_')))
.Select(g => g.OrderBy(x => x.Substring(x.IndexOf('_')).Contains("CREATE"))
.ThenBy(x => x.Substring(x.IndexOf('_')).Contains("INSERT"))
.ThenBy(x => x.Substring(x.IndexOf('_')).Contains("UPDATE"))
.ThenBy(x => x.Substring(x.IndexOf('_')).Contains("DELETE")));
上述查询按名称“Avinash”进行分组,但不适用于自定义排序。请帮忙。
更新
请查看更新的查询,但仍未正确排序
答案 0 :(得分:2)
使用Split提取字符串的相关部分。将结果转换为大写,这似乎是您尝试中遗漏的。另外,通过使用数组来保存自定义排序顺序,然后使用Array.IndexOf从中获取排序顺序,而不是多个OrderBy / ThenBy,可以缩短它。
var ordering = new [] {"CREATE", "INSERT", "UPDATE", "DELETE"};
var results = shortfilenames.GroupBy(s => s.Split('_')[0])
.Select(g => g.OrderBy(x => Array.IndexOf(ordering, x.Split('_')[1].Split('.')[0].ToUpper())));
答案 1 :(得分:1)
这似乎是你想要的:
var shortfilenames = new List<string>(){"Avinash_Create.sql" , "Avinash_Insert.sql" , "Avinash_Update.sql" , "Avinash_Delete.sql"};
var userGroups = shortfilenames
.Select(fn =>
{
string fileName = Path.GetFileNameWithoutExtension(fn);
string[] nameAndAction = fileName.Split('_');
return new
{
extension = Path.GetExtension(fn),
fileName,
name = nameAndAction[0],
action = nameAndAction[1]
};
})
.GroupBy(x => x.name)
.Select(g => g.OrderByDescending(x => x.action.Equals("CREATE", StringComparison.InvariantCultureIgnoreCase))
.ThenByDescending(x => x.action.Equals("INSERT", StringComparison.InvariantCultureIgnoreCase))
.ThenByDescending(x => x.action.Equals("UPDATE", StringComparison.InvariantCultureIgnoreCase))
.ThenByDescending(x => x.action.Equals("DELETE", StringComparison.InvariantCultureIgnoreCase))
.ToList());
foreach (var ug in userGroups)
foreach (var x in ug)
Console.WriteLine("{0} {1}", x.name, x.action);
打印出来:
Avinash Create
Avinash Insert
Avinash Update
Avinash Delete
假定文件名始终包含下划线。