我该如何解决这个问题?我正在尝试使用LINQ,但我找不到办法。
我有两个列表:
System.IO
)第一个List包含x个File对象。
第二个列表包含表示扩展名的x个字符串,例如{".txt",".exe"}
。
我需要在其他File对象之前使用包含在第二个List中的属性Extension的File对象。
最详细的例子是:
1)List有这些File对象:
File {Name="1" Extension = ".exe"}
File {Name="2" Extension = ".txt"}
File {Name="3" Extension = ".ini"}
File {Name="4" Extension = ".exe"}
File {Name="5" Extension = ".zip"}
File {Name="6" Extension = ".jpg"}
2)列表包含以下值:{“。txt”,“。exe”}
有序列表将是:
File {Name="1" Extension =".exe"}
File {Name="2" Extension =".txt"}
File {Name="4" Extension =".exe"}
...Remaining
File
Objects, doesn't matter the position.
我尝试过的LINQ:
var sorted = files.OrderBy(cus => precedenceExstensions.Contains(cus.Extension));
答案 0 :(得分:0)
您想按降序排序:
files.OrderByDescending(f => extensions.Contains(f.Extension));
Linq会在false
之前订购布尔true
,你想要它们的顺序相反。
完整代码:
using System;
using System.Collections.Generic;
using System.Linq;
public class File
{
public string Name;
public string Extension;
public override string ToString()
{
return string.Format("File: {0}, Extension: {1}", Name, Extension);
}
}
public class Program
{
public static void Main()
{
var files = new List<File>()
{
new File {Name="1", Extension = ".exe"},
new File {Name="2", Extension = ".txt"},
new File {Name="3", Extension = ".ini"},
new File {Name="4", Extension = ".exe"},
new File {Name="5", Extension = ".zip"},
new File {Name="6", Extension = ".jpg"}
};
var extensions = new[]{".txt", ".exe"};
Console.WriteLine(string.Join("\n", files.OrderByDescending(f => extensions.Contains(f.Extension))));
}
}
您可以在dotnetfiddle here上看到它。