marknery
marknery

Reputation: 1543

Linq query only returning first item of array

Let the string projects equal "p1,p2,p3" and in the database the identifier for each exists as follows p1 = 1 ,p2 = 2, p3 = 3. Only the first project in the list is being returned in my query, any thoughts on why?

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 This issue was whitespace in the string I changed

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

to

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

Upvotes: 1

Views: 726

Answers (1)

Pawan Mishra
Pawan Mishra

Reputation: 7268

The following code uses the same logic, the one you have mentioned in your question. I have created dummy data. The code is behaving as expected i.e. the output is the prjID corresponding to each prjName.

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;}
}

Upvotes: 4

Related Questions