我收到了一个文件列表,以及它们所在的文件夹
我只能在任何阶段处理每个文件夹1个文件 - 并且需要返回 每个文件夹的第一个文件(处理完这些第一个文件后,它们将从列表中删除)
因此,如果我有输入:
/Foldername1/OrderNo1.csv
/Foldername2/OrderNo2.csv
/Foldername1/OrderNo3.csv
/Foldername3/OrderNo4.csv
/Foldername2/OrderNo5.csv
它应该返回
/FolderName1/OrderNo1.csv
/FolderName2/OrderNo2.csv
/FolderName3/OrderNo4.csv
public void Main()
{
RunThis();
}
public class Order
{
public string OrderNo;
public int CustomerID;
}
private void RunThis()
{
List<Order> o = new List<Order>()
{
new Order { OrderNo = "/Foldername1/OrderNo1.csv",CustomerID = 1},
new Order { OrderNo = "/Foldername2/OrderNo2.csv",CustomerID = 7},
new Order { OrderNo = "/Foldername1/OrderNo3.csv",CustomerID = 8},
new Order { OrderNo = "/Foldername3/OrderNo4.csv",CustomerID = 12},
new Order { OrderNo = "/Foldername2/OrderNo5.csv",CustomerID = 8},
};
Console.WriteLine(o);
}
这可以通过Linq实现,还是只能通过 创建2个数组 1.保留已处理文件夹的列表 2.保留文件夹
中的第一个文件列表Loop each filename
if processed folder does not contain files Directory Name
add foldername to processedfolders
add file to list of first files
end if
next
答案 0 :(得分:2)
按directory name分组并从每个组中获取第一个文件:
List<Order> list = new List<Order>()
{
new Order { OrderNo = "/Foldername1/OrderNo1.csv",CustomerID = 1},
new Order { OrderNo = "/Foldername2/OrderNo2.csv",CustomerID = 7},
new Order { OrderNo = "/Foldername1/OrderNo3.csv",CustomerID = 8},
new Order { OrderNo = "/Foldername3/OrderNo4.csv",CustomerID = 12},
new Order { OrderNo = "/Foldername2/OrderNo5.csv",CustomerID = 8},
};
var files = list.GroupBy(o=>Path.GetDirectoryName(o.OrderNo)).Select(o=>o.First());
答案 1 :(得分:1)
在LINQ中,处理此问题的方法是对记录进行分组,根据需要对组进行排序,然后使用First
方法从每个组中返回单个项目。
在您的特定情况下,分组术语将是文件夹名称,您可以使用Path.GetDirectoryName
方法提取该名称。可以在分组操作之前完成排序,并且应该保留所请求的顺序:
var query =
from ord in list
orderby ord.OrderNo
group ord.OrderNo by Path.GetDirectoryName(ord.OrderNo) into grp
select grp.First();
由此产生的记录:
/Foldername1/OrderNo1.csv
/Foldername2/OrderNo2.csv
/Foldername3/OrderNo4.csv