Buck
Buck

Reputation: 599

Compiling Error with LINQ Sorting Code Using List<T>

Compilation Error: "The name 'b' does not exist in the current context"

Code:

    List<PositionValues> list = new List<PositionValues>();
    PositionValues item1 = new PositionValues();
    item1.Position = 2;
    item1.Value = 44;
    list.Add(item1);

    PositionValues item2 = new PositionValues();
    item2.Position = 1;
    item2.Value = 33;
    list.Add(item2);


    PositionValues item3 = new PositionValues();
    item3.Position = 1;
    item3.Value = 22;
    list.Add(item3);


    var resultList = from b in list 
                     group b by b.Position into g 
                     orderby b.Value select b;

The above code relies on this struct:

public struct PositionValues
{
    /// <summary>
    /// The position.
    /// </summary>
    public int Position;

    /// <summary>
    /// The position.
    /// </summary>
    public double Value;
}

I am hoping to get the following sort order:

resultList[0] {1, 22}
resultList[1] {1, 33}
resultList[2] {2, 44}

"Position" is first in the parenthesis and "Value" is second.

Upvotes: 1

Views: 116

Answers (3)

Timothy Shields
Timothy Shields

Reputation: 79541

Or, if you want the query style,

var query =
    from b in list
    orderby b.Position, b.Value
    select b;

Upvotes: 1

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174397

Based on the expected result you posted, you don't need to use group by.

What you want is more something like this:

var result = list.OrderBy(x => x.Position).ThenBy(x => x.Value);

Upvotes: 3

Francis P
Francis P

Reputation: 13665

You've used b into a group g, so now use g. You must also orderby b before grouping into g.

var resultList = from b in list orderby b.Value group b by b.Position into g select g;

Upvotes: 0

Related Questions