Accepted answer

You would need to split by the comma and then order by the index. Since split will return an array you would need to create a list first:

slot candidate = (from s in slots
    let parts = s.Ids.Split(',')
    where parts.Contains(searchItem)
    orderby Array.IndexOf(parts, searchItem)
    select s).FirstOrDefault();

detail: the let part allows you to save the split result temporarily in the variable parts. This way you can avoid spliting again when the order by clause is executed.


 private slot search(List<slot> slots, string searchItem)
                for (int i = 0; i < slots.Count; i++)
                    var slotIds = slots[i].Ids.Split(',');
                    if (slotIds.contains(searchItem))
                        return slots[i];

                return null;


You could use

var result = slots.Select(x=>x.Ids.Split(new[]{','}))
                      .OrderBy(x=>Math.Abs((Array.IndexOf(x,itemToSearch) + 1) - Convert.ToInt32(itemToSearch)))


Try this approach that avoids all of the muck IndexOf or Contains:

List<slot> slots = new List<slot>()
    new slot { Ids = "2,3,4,6,8,9,1" },
    new slot { Ids = "10,11,12,13,1,7" },
    new slot { Ids = "1,4,6,5,10,11,29,40,7" },

IEnumerable<IGrouping<string, slot>> query =
    from slot in slots
    let Ids = slot.Ids.Split(',')
    from x in Ids.Select((number, index) => (number, index))
    orderby x.index
    group slot by x.number;

Dictionary<string, slot> map = query.ToDictionary(x => x.Key, x => x.First());

With this you get the following:

  • map["1"] gives slot { Ids = "1,4,6,5,10,11,29,40,7" }
  • map["7"] gives slot { Ids = "10,11,12,13,1,7" }

Related Articles