Tom Gullen
Tom Gullen

Reputation: 61773

ASP.net c# LINQ for loop

// Load all the links
ArtworkingDataContext dc = new ArtworkingDataContext();
var q = (from Labels in dc.tblArtworkLabels where Labels.templateID == this.ID select new { LabelID = Labels.ID });

// Create labels array
this.Labels = new ArtworkLabel[q.Count()];
for (int i = 0; i < q.Count(); i++)
{
    this.Labels[i] = new ArtworkLabel(q.LabelID);
}

The q.LabelID isn't working, I can't really use a foreach because I have to invoke a new ArtworkLabel on each iteration.

Upvotes: 1

Views: 3694

Answers (5)

BanMe
BanMe

Reputation: 133

I tried this recently, a linq for loop.. this is what I came up with..

        var query = from ii in Enumerable.Range(0, xml.AllIndexesOf("<item").Count())
                    where ii < xml.AllIndexesOf("<item").Count()
                    select new { Start = xml.AllIndexesOf("<item").ToList()[sii], Count = xml.AllIndexesOf("</item").ToList()[sii] - xml.AllIndexesOf("<item").ToList()[sii] };

Upvotes: 0

Mark Coleman
Mark Coleman

Reputation: 40863

You should be able to do it all in one linq statement.

ArtworkingDataContext dc = new ArtworkingDataContext();
this.Labels = (from Labels in dc.tblArtworkLabels where Labels.templateID == this.ID select new ArtworkLabel(Labels.ID)).ToArray();

Upvotes: 1

BrokenGlass
BrokenGlass

Reputation: 161002

This would work:

var queryList = q.ToList();
for (int i = 0; i < queryList.Count; i++)
{
    this.Labels[i] = new ArtworkLabel(queryList[i].LabelID);
}

Also you can directly project from your query:

this.Labels = dc.tblArtworkLabels
                .Where( x=> x.templateId == this.Id)
                .Select( x=> new ArtworkLabel(x.ID))
                .ToArray();

Upvotes: 1

Grant Thomas
Grant Thomas

Reputation: 45058

You could potentially just do this, right?

ArtworkingDataContext dc = new ArtworkingDataContext();

this.Labels = 
    from label in dc.tblArtworkLabels 
    where label.templateID == this.ID
    select new ArtworkLabel(label.ID).ToArray();

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

Try like this:

this.Labels = q.Select(x => new ArtworkLabel(x.LabelID)).ToArray();

Upvotes: 1

Related Questions