user3167910
user3167910

Reputation: 85

Increment in LINQ Query

Hello I have the following code which returns me List of type Listitem. I want to increase the value by one for every ListItem Selected.

public static List<System.Web.UI.WebControls.ListItem> GetMyCompassTUTListContent(List<int> ContentID, Int32 CountryID)
{
    int Counter = 0;
    List<System.Web.UI.WebControls.ListItem> litems = new List<System.Web.UI.WebControls.ListItem>();
    using (DbDataContext objContext = new DbDataContext())
    {
        if (CountryID == (int)MyCompassBLL.Constants.Country.Australia)
        {
            litems = objContext.Contents.Where(x => ContentID.Contains(x.ID)).Select(x => new System.Web.UI.WebControls.ListItem { Text = x.Text, y = (y + 1) }).ToList();
        }
        else
        {
            litems = objContext.ContentCountries.Where(x => ContentID.Contains(x.ContentID) && x.CountryID == CountryID).Select(x => new System.Web.UI.WebControls.ListItem { Text = x.Text, Value = (Counter + 1).ToString() }).ToList();
        }
    }
    return litems;
}

Please help me in this. I am not able to that since I am not able to find the way of how to reassign value to variable counter after increment.

Thanks in advance

Upvotes: 3

Views: 6768

Answers (2)

Servy
Servy

Reputation: 203827

There is an overload of Select that also provides the index of the current item. You can use that. However, most DB query providers don't support it, so you'll need to do your DB query, then ensure that the Enumerable overload of Select is called to add the index:

public static List<ListItem> GetMyCompassTUTListContent(
    List<int> ContentID, Int32 CountryID)
{
    //Note this is IEnumerable, not IQueryable, this is important.
    IEnumerable<string> query;
    using (DbDataContext objContext = new DbDataContext())
    {

        if (CountryID == (int)MyCompassBLL.Constants.Country.Australia)
        {
            query = objContext.Contents.Where(x => ContentID.Contains(x.ID))
                .Select(x => x.Text);
        }
        else
        {
            query = objContext.ContentCountries
                .Where(x => ContentID.Contains(x.ContentID)
                    && x.CountryID == CountryID)
                .Select(x => x.Text);
        }
        return query.Select((text, index) => new ListItem
        {
            Text = text,
            Value = (index + 1).ToString(),
        })
        .ToList();
    }
}

Upvotes: 7

Hugo S. Mendes
Hugo S. Mendes

Reputation: 1086

Use ++Counter instead of ( Counter + 1)

[UPDATE]

try to increment your Counter before put it into the Select():

else
    { 
        Counter++;
        litems = objContext.ContentCountries.Where(x => ContentID.Contains(x.ContentID) && x.CountryID == CountryID).Select(x => new System.Web.UI.WebControls.ListItem { Text = x.Text, Value = Counter.ToString() }).ToList();
    }

Upvotes: -1

Related Questions