问题描述
我有以下情况:
Hi,
I have the following scenario:
public Class Form
{
public string Name {get; set;}
public string FormID {get; set;}
public string Path {get; set;}
}
List<Form>pdfdoc = new List<Form>{
new Form{ Name="FormA", FormID ="1", Path="D:/Temp/"},
new Form{ Name="FormB", FormID ="2", Path="D:/Temp/"},
new Form{ Name="FormC", FormID ="3", Path="D:/Temp/"},
new Form{ Name="FormC", FormID ="4", Path="D:/Temp/"},
new Form{ Name="FormD", FormID ="5", Path="D:/Temp/"},
new Form{ Name="FormD", FormID ="6", Path="D:/Temp/"},
new Form{ Name="FormE", FormID ="7", Path="D:/Temp/"},
new Form{ Name="FormF", FormID ="8", Path="D:/Temp/"},
new Form{ Name="FormG", FormID ="8", Path="D:/Temp/"},
new Form{ Name="FormH", FormID ="8", Path="D:/Temp/"},
};
我希望检查列表是否包含FormC和FormD,然后将列表拆分为三个列表,第一个列表包含FormA和FormB,第二份清单包含FormC,FormC,FormD和FormD,第三份清单包含FormE,FormF,FormG和FormH。有没有办法?
FormC和FormD表格可以在列表的任何位置重复任意次数。总列表可以包含更多数量的表单。请帮忙。
I want that to check if the list contains FormC and FormD and then split the list into three lists, the first list containing FormA and FormB,second list containing FormC, FormC, FormD and FormD and the third list containing FormE,FormF,FormG and FormH. Is there any possible way?
The forms FormC and FormD can repeat any number of times at any position in the list. The total list may have more any number of forms. Please help.
推荐答案
var x = from form in pdfdoc where form.Name == "FormA" || form.Name == "FormB" select form;
var y = from form in pdfdoc where form.Name == "FormC" || form.Name == "FormD" select form;
var z = from form in pdfdoc where form.Name != "FormA" && form.Name != "FormB"
&& form.Name != "FormC" && form.Name != "FormD"
select form;
List<Form> list1, list2, list3;
SplitList(pdfdoc, out list1, out list2, out list3);
这是方法:
And this is the method:
public static void SplitList(List<Form> mainList, out List<Form> firstList, out List<Form> secondList, out List<Form> thirdList)
{
firstList = null;
secondList = null;
thirdList = null;
if (mainList.All(l => l.Name != "FormC") || mainList.All(l => l.Name != "FormD"))
return;
firstList = CreateList(mainList, "FormA", "FormB");
secondList = CreateList(mainList, "FormC", "FormD");
thirdList = CreateList(mainList, "FormE", "FormF", "FormG", "FormH");
}
private static List<Form> CreateList(List<Form> list, params string[] formNames)
{
var temp = new List<Form>();
foreach (var s in formNames)
{
temp.AddRange(list.Where(l => l.Name == s));
}
return temp;
}
或者,您可以将此方法用于thirdList:
Or, you can use this method for thirdList:
private static List<Form> CreateResidualList(List<Form> list, params List<Form>[] lists)
{
return lists.Aggregate(list, (current, listTemp) => current.Where(l => !listTemp.Contains(l)).ToList());
}
并且:
And:
thirdList = CreateResidualList(mainList, firstList, secondList);
这篇关于根据某些条件将列表拆分为三个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!