Linq查询只返回数组的第一项

时间:2011-11-06 16:52:27

标签: c# linq

让字符串项目等于“p1,p2,p3”,并且在数据库中每个的标识符存在如下p1 = 1,p2 = 2,p3 = 3.只有列表中的第一个项目在我的查询,有关为什么的任何想法?

private List<int> getProjects(string projects)
    {

        String[] projectArray = projects.Split(',');

        QMOIIEntities db = new QMOIIEntities();

        var projectList = db.wbs_projects
          .Where(x => projectArray.Contains(x.prjName))
          .Select(x => x.prjID).ToList();

        return projectList;
    }

* * UPDATE 这个问题是我改变的字符串中的空格

String[] projectArray = projects.Split(',');

 String[] projectArray = projects.Trim().Split(',');

1 个答案:

答案 0 :(得分:4)

以下代码使用相同的逻辑,即您在问题中提到的逻辑。我创建了虚拟数据。代码按预期运行,即输出是对应于每个prjName的prjID。

void Main()
{
    string projects = "p1,p2,p3";
    List<string> projectArray = projects.Split(',').ToList();

    TestEntities db = new TestEntities();
    db.wbs_projects = new List<TestEntities>();
    db.wbs_projects.Add(new TestEntities(){prjName = "p1",prjID="Test1"});
    db.wbs_projects.Add(new TestEntities(){prjName = "p2",prjID="Test2"});
    db.wbs_projects.Add(new TestEntities(){prjName = "p3",prjID="Test3"});

    var projectList = db.wbs_projects
      .Where(x => projectArray.Contains(x.prjName))
      .Select(x => x.prjID).ToList();

    foreach(var item in projectList)
    {
        Console.WriteLine(item);//Test1,Test2,Test3
    }

}

public class TestEntities
{   
    public List<TestEntities> wbs_projects{get;set;}

    public string prjName{get;set;}
    public string prjID{get;set;}
}