如何在LInq中编写简单代码

时间:2010-05-03 05:40:58

标签: c#

我的NotSelectedList中有以下内容。

public List<TestModel> SelectedList = new List<TestModel>();
public List<TestModel>NotSelectedList =  new List<TestModel>();
NotificationDetailsModel projects = new NotificationDetailsModel();
projects.ProjectID = Convert.ToInt32(Row["ProjectID"]);
projects.Valid= Convert.ToBoolean(Row["Validity"]);
NotSelectedList.Add(projects);

如何在LINQ中编写一个简单的代码,从NotSelectedList中选择Validity == True并将数据存储在SelectedList中?

3 个答案:

答案 0 :(得分:4)

var query = from ns in NotSelectedList
            from n in SelectedList
            where ns.Valid && ns.ProjectID == n.ProjectID
            select ns;

希望这会对你有所帮助

答案 1 :(得分:1)

以下将从NotSelectedList中选择Validity = true的项目并将它们放在SelectedList中:

SelectedList.AddRange(NotSelectedList.Where(item => item.Validity));

答案 2 :(得分:0)

试试这个:

var results = NotSelectedList.Where(x => x.Valid);
foreach (var item in results)
    SelectList.Add(item);

虽然出于性能原因,你最好不要做这样的事情:

foreach (var item in NotSelectedList)
{
    if (item.Valid)
        SelectList.Add(item);
}