Ognjen
Ognjen

Reputation: 1195

problem with linq (C#)

 var pom= from k in dataContext.student_gods
                            where k.skgod==System.Convert.ToString(2002/03)
                            select k;
            foreach(var i in pom){
            var predmeti = from m in dataContext.student1s
                           where m.id_stud ==System.Convert.ToString(i.id_stud)

                           select m;


            }
          return View(predmeti);

This is code after suggestions. I have one error: the name predmeti does not exist in current context. If declare var predmeti before foreach loop I dont know how to initialize

Upvotes: 0

Views: 163

Answers (4)

Marc Gravell
Marc Gravell

Reputation: 1062770

I think you are over-complicating this, and risking the infamous foreach/capture issue (since LINQ uses deferred execution). Perhaps just:

var pom= from k in dataContext.student_gods
         where k.skgod==System.Convert.ToString(2002/03)
         select k.id_stud;
var list = pom.ToList();
var predmeti = from m in dataContext.student1s
               where list.Contains(m.id_stud)
               select m;
return View(predmeti);

Upvotes: 1

Fredrik Mörk
Fredrik Mörk

Reputation: 158309

This code line looks really odd to me:

where k.skgod==System.Convert.ToString(2002/03);

This means that you will get all records where k.skgod = 667. Is this your intention?

Still, as others have already mentioned; the return in your foreach will effectively prevent the code from returning anything else than the first object in the collection.

Upvotes: 1

Graviton
Graviton

Reputation: 83254

Is it because you are returning the function in the foreach loop?

foreach(var i in pom){
            var predmeti = from m in dataContext.student1s
                           where m.id_stud ==System.Convert.ToString(i.id)

                           select m;

            return View(predmeti);
}

This means that the function will quit at the first i.

Upvotes: 0

Elisha
Elisha

Reputation: 23770

The return is in the middle of the foreach loop. I am not sure what the context is but you may want to yield return instead of build the view with the whole collection.

In this case, you exit from the method after the first item in the collection in which you're iterating.

Upvotes: 3

Related Questions