Search value from comma separated string List based on index using C# and VB.Net in ASP.Net

Last Reply one month ago By dharmendr

Posted one month ago

Hi Team,

How to search the list and take based on the index value in c#

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

In above all the list have "1" but If I search with one then it should return the 3d list because of the index, so just need to compare the index also and need to take that one.

IF I search with "7" then it should return 2nd list

How to achieve this?

You are viewing reply posted by: dharmendr one month ago.
Posted one month ago

Hi bebins,

Refer below code.

C#

protected void Save(object sender, EventArgs e)
{
    string searchId = "1";
    List<slot> slots = new List<slot>();
    slots.Add(new slot { Ids = "2,3,4,6,8,9,1" });
    slots.Add(new slot { Ids = "10,11,12,13,1,7" });
    slots.Add(new slot { Ids = "1,4,6,5,10,11,29,40,7" });
    List<ItemIndex> indexes = new List<ItemIndex>();
    for (int i = 0; i < slots.Count; i++)
    {
        int index = Array.FindIndex(slots[i].Ids.Split(',').ToArray(), t => t.Split(',').Contains(searchId));
        if (index != -1)
        {
            ItemIndex item = new ItemIndex();
            item.Index = i;
            item.ExistingIndex = index;
            indexes.Add(item);
        }
    }
    if (indexes.Count > 0)
    {
        slot result = slots[indexes.OrderBy(x => x.ExistingIndex).FirstOrDefault().Index];
    }
}

public class slot
{
    public string Ids { get; set; }
}

public class ItemIndex
{
    public int Index { get; set; }
    public int ExistingIndex { get; set; }
}

VB.Net

Protected Sub Save(ByVal sender As Object, ByVal e As EventArgs)
    Dim searchId As String = "1"
    Dim slots As List(Of slot) = New List(Of slot)()
    slots.Add(New slot With {.Ids = "2,3,4,6,8,9,1"})
    slots.Add(New slot With {.Ids = "10,11,12,13,1,7"})
    slots.Add(New slot With {.Ids = "1,4,6,5,10,11,29,40,7"})
    Dim indexes As List(Of ItemIndex) = New List(Of ItemIndex)()
    For i As Integer = 0 To slots.Count - 1
        Dim index As Integer = Array.FindIndex(slots(i).Ids.Split(","c).ToArray(), Function(t) t.Split(","c).Contains(searchId))
        If index <> -1 Then
            Dim item As ItemIndex = New ItemIndex()
            item.Index = i
            item.ExistingIndex = index
            indexes.Add(item)
        End If
    Next

    If indexes.Count > 0 Then
        Dim result As slot = slots(indexes.OrderBy(Function(x) x.ExistingIndex).FirstOrDefault().Index)
    End If
End Sub

Public Class slot
    Public Property Ids As String
End Class

Public Class ItemIndex
    Public Property Index As Integer
    Public Property ExistingIndex As Integer
End Class