Search code examples
c#sql-order-byienumerable

IEnumerable order by positional index


I am trying to order an IEnumerable object by an index positioning. Example:

IEnumerable:

//index  1       2    3
[0] {"result1", "3", "15"}
[1] {"result2", "4", "3"}
[2] {"result3", "1", "1"}
[3] {"result4", "5", "11"}

I'd like to order by the 3'rd index positioning and my expected results would be this:

[0] {"result3", "1", "1"}
[1] {"result2", "4", "3"}
[2] {"result4", "5", "11"}
[3] {"result1", "3", "15"}

I've tried something like this but haven't had any luck:

private void UpdateGrouping(IEnumerable<List<string>> grouping)
{
    grouping.OrderBy(p => grouping.IndexOf(3));
}

Solution

  • You need to overwrite the result, pass the grouping by ref and overwrite it inside your function:

    I supose the ordering index is an integer, else change acordingly

    private void UpdateGrouping(ref IEnumerable<List<string>> grouping)
    {
        grouping = grouping.OrderBy(p => int.TryParse(p[2], out int index)?index:0);
    }
    

    or return the ordered list and overwrite outside your function

    private IEnumerable<List<string>> UpdateGrouping(IEnumerable<List<string>> grouping)
    {
        return grouping.OrderBy(p => int.TryParse(p[2], out int index)?index:0);
    }