user5968830
user5968830

Reputation:

LINQ in c#: Foreach inside linq

I have trouble selecting rows in a dynamic way.

foreach (var item in _listBox.SelectedItems)
{
   Treinen treinData = (Treinen)item;
   Debug.WriteLine(treinData.Name);
}

Here i get the selected items name from a listbox with about 60 names in, depending on the selection I want to get the representing SQL data for those selected. I think this requires to append a dynamic .Where clause.

   ObjectQuery<Fouten> fouten = eventsEntities.Foutens;

   loadedData =
   (from fout in fouten
   where datumStart <= fout.Datum && datumEnd >= fout.Datum

   .... here should where be extended in some way, for example:
   && foreach (var item in _listBox.SelectedItems)
   {
     Treinen treinData = (Treinen)item;
     where fout.Treinen.Name == treinData.Name
   }
   orderby fout.Datum, fout.Time

   select new
   {
      Datum = fout.Datum,
      Time = fout.Time,
      FoutCode = fout.FoutCode,
      Omschrijving = fout.Omschrijving,
      Teller = fout.Teller,
      Module = fout.Module.ToUpper(),
      FoutId = fout.FoutId,
      TreinId = fout.TreinId
   }).AsEnumerable().Select(x => new Fouten
   {
      Datum = x.Datum,
      Time = x.Time,
      FoutCode = x.FoutCode,
      Omschrijving = x.Omschrijving,
      Teller = x.Teller,
      Module = x.Module,
      FoutId = x.FoutId,
      TreinId = x.TreinId
   })
   .ToList();

Obviously that doesn't work but hopefully it makes sense to what I'm trying to accomplish. Right now I get the data for all items instead of the selected ones. Anyone has a idea on how to solve?

Upvotes: 2

Views: 1514

Answers (1)

Marcel B
Marcel B

Reputation: 518

I suppose your "Treinen" has an ID-Field (or Property) in it and since you have your fout.TreinId it is easier to go for the ID.

you can fill your ID-list before going into the query and then just check if your ID is in the List:

List<int> treinenIds = new List<int>();
foreach (var item in _listBox.SelectedItems)
    treinenIds.Add(((Treinen)item).Id);

ObjectQuery<Fouten> fouten = eventsEntities.Foutens;

loadedData =
(from fout in fouten

    where datumStart <= fout.Datum && datumEnd >= fout.Datum

    //where-clause
    where treinenIds.Contains(fout.TreinId)

orderby fout.Datum, fout.Time

select new
{
    Datum = fout.Datum,
    Time = fout.Time,
    FoutCode = fout.FoutCode,
    Omschrijving = fout.Omschrijving,
    Teller = fout.Teller,
    Module = fout.Module.ToUpper(),
    FoutId = fout.FoutId,
    TreinId = fout.TreinId
}).AsEnumerable().Select(x => new Fouten
{
    Datum = x.Datum,
    Time = x.Time,
    FoutCode = x.FoutCode,
    Omschrijving = x.Omschrijving,
    Teller = x.Teller,
    Module = x.Module,
    FoutId = x.FoutId,
    TreinId = x.TreinId
})
.ToList();

I'm not sure if the .Contains is supported in the query but if it is then this code should work for your Example.

Upvotes: 2

Related Questions