基于特定值将列表拆分为两个 [英] split list into two based on certain value

查看:120
本文介绍了基于特定值将列表拆分为两个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有以下情况:



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="Form1", FormID ="1", Path="D:/Temp/"},
new Form{ Name="Form2", FormID ="2", Path="D:/Temp/"},
new Form{ Name="Form3", FormID ="3", Path="D:/Temp/"},
new Form{ Name="Form4", FormID ="4", Path="D:/Temp/"},
new Form{ Name="Form5", FormID ="5", Path="D:/Temp/"},
new Form{ Name="Form6", FormID ="6", Path="D:/Temp/"},
new Form{ Name="Form7", FormID ="7", Path="D:/Temp/"},
new Form{ Name="Form8", FormID ="8", Path="D:/Temp/"},
};





我希望检查列表是否包含Form4然后将列表拆分为两个列表,第一个列表包含Form1,Form2,Form3,另一个列表包含Form5,Form6,Form7,Form8。有没有办法?



I want that to check if the list contains Form4 and then split the list into two lists, the first list containing Form1,Form2,Form3 and the other containing Form5,Form6,Form7,Form8. Is there any possible way?

推荐答案

var index = pdfdoc.IndexOf(pdfdoc.Find(f => f.Name.Equals("Form")));

if (index > 0)
{
    var list1 = pdfdoc.GetRange(0, index);
    var list2 = pdfdoc.GetRange(index + 1, pdfdoc.Count - index - 1);
}




这是其中一种方式:





string [] str = new string [] {1,2,3};

List> method1 = method(str,pdfdoc);

List> method(string [] str,List aa)

{

List> dd = new List>();

List dd1 =(from s in str

from ss in aa

其中s == ss。 FormID

select ss)。ToList();

List dd2 = aa.Except(dd1).ToList();

dd.Add (dd1);

dd.Add(dd2);

return dd;

}
Hi,
This is one of the way:


string[] str = new string[] { "1", "2", "3" };
List> method1 = method(str, pdfdoc);
List> method(string[] str, List aa)
{
List> dd = new List>();
List dd1 = (from s in str
from ss in aa
where s == ss.FormID
select ss).ToList();
List dd2 = aa.Except(dd1).ToList();
dd.Add(dd1);
dd.Add(dd2);
return dd;
}


Hi Saket,



使用LINQ,在进行此类操作时非常漂亮。



使用下面的代码:

--------------------- -----------

Hi Saket,

Use LINQ, it's quite beautiful while doing such manipulations.

Use the code below:
--------------------------------
List<Form> List1 = (from docs in pdfdoc where (docs.FormID.CompareTo("4") < 0) select docs).ToList();




List<Form> List2= (from docs in pdfdoc where (docs.FormID.CompareTo("4") > 0) select docs).ToList();



---- ----------------------------





希望它有所帮助!



快乐编码:)


--------------------------------


Hope it helps!

Happy Coding :)


这篇关于基于特定值将列表拆分为两个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆