user8428004
user8428004

Reputation:

How do i sort my listview alphabetically?

So i have this listview, and i want to make it alphabetically sorting. do someone know if you can do it? and if you know how you can do it, then show me the code. LOOKING FOR HELP!!

this is my Xaml.cs code:

namespace App2
{
public partial class MainPage : ContentPage
{
    List<Kontakter> kontakter = new List<Kontakter>
    {
        new Kontakter
        {
        Fuldenavn = "Name One (NO)",
        Tlfnr = 12345678
        },
        new Kontakter
        {
            Fuldenavn = "Another Name (AN)",
            Tlfnr = 23456789
        },
        new Kontakter
        {
            Fuldenavn = "Third Name (TN)",
            Tlfnr = 34567890
        },
        new Kontakter
        {
            Fuldenavn = "Yet Another (YA)",
            Tlfnr = 45678901
        }
    };

    public MainPage()
    {
        InitializeComponent();

        NameslistView.ItemsSource = kontakter;
    }

    private void MainSearchBar_SearchButtonPressed(object sender, EventArgs e)
    {
        var keyword = MainSearchBar.Text;
        NameslistView.ItemsSource = kontakter.Where(obj => (obj.Fuldenavn.Contains(keyword) || obj.Tlfnr.ToString().Contains(keyword)));
    }
}
}

this is my Xmal code:

<ListView x:Name="NameslistView" HasUnevenRows="True">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Label Text="{Binding Fuldenavn}" />
                <Label Text="{Binding Tlfnr}" />
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Upvotes: 2

Views: 6875

Answers (2)

Gagan S Patil
Gagan S Patil

Reputation: 11

use Sort and provide condition

kontakter.Sort((x, y) => x.Fuldenavn[0].CompareTo(y.Fuldenavn[0]));

where [0] represent 1st letter of Fuldenavn so that it will be sorted by alphabetical order.

Upvotes: 1

Mighty Badaboom
Mighty Badaboom

Reputation: 6155

You could use the LINQ method OrderBy for this.

Sorts the elements of a sequence in ascending order according to a key.

var sorted = kontakter.OrderBy(x => x.Fuldenavn)
                      .ToList();

Have a read at 101 LINQ-Samples for more information.

EDIT

public MainPage()
{
    InitializeComponent();

    //Order the contacts
    var sorted = kontakter.OrderBy(x => x.Fuldenavn)
                          .ToList();

    //Set the ItemsSource with the ordered contacts
    NameslistView.ItemsSource = sorted;
}

Upvotes: 9

Related Questions