Home > database >  Group Columns of a List in a ListView Xamarin
Group Columns of a List in a ListView Xamarin

Time:01-25

I'm new to Xamarin and C#, and I'd like your help with the following: I have a list organized like this:

ID      School   Student    RegistrationDate
1         A       Ana      21/01/2021 13:00:02
2         A       John     21/01/2021 10:00:02
3         B       Anthony  13/05/2021 10:00:02
4         B       Ana      10/02/2020 10:00:02
5         B       Albert   21/01/2022 10:00:02
6         C       Ana      21/01/2021 10:00:02
7         C       Sheila   22/01/2021 10:00:02
8         C       Ana      26/12/2021 10:00:02

And I intend to show in a ListView only one record of each School.. Like this:

School  RegistrationDate
A        21/01/2021
B        13/05/2021
C        26/12/2021

Estou usando o SQlite, que me retorna a lista com os dados. Este é o meu MVVM:

 public ObservableCollection<StudentSchool> sc = new ObservableCollection<StudentSchool>();
    public ObservableCollection<StudentSchool> SC
    {
        get => sc;
        set => sc= value;
    }
List<StudentSchool> tmp = await  App.Database.GetSchoolStudent();
   public GetData{
 foreach (var item in tmp)
  {
      var newList = tmp
      .GroupBy(x => new { x.School });  
       //How to fill my SC list?                                                                                                   
    }
 }   
                

Este é a minha View:

<ListView ItemsSource="{Binding MyList}">
            <ListView.Header>
                <Grid RowDefinitions="*"
                          ColumnDefinitions="*,*,*">
        <Label Grid.Row="0" Grid.Column="0"Text="Student"/>
         <Label Grid.Row="0" Grid.Column="1" Text="RegistrationDate" />        
                </Grid>
            </ListView.Header>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Grid RowDefinitions="Auto"
                                  ColumnDefinitions="*,*,*">
                            <Label Grid.Row="0" Grid.Column="0" Text="{Binding Student}" />
                            <Label Grid.Row="0" Grid.Column="1" Text="{Binding RegistrationDate, StringFormat='{}{0:dd/MM/yyyy}'}" />
                            
                            </Grid>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

How to fill my SC list?

CodePudding user response:

You can achieve using LINQ:

var result = tmp.GroupBy(x => x.School)
.Select(y => new { y.First().School, y.First().RegistrationDate })
.OrderBy(z => z.RegistrationDate);

and then:

foreach( var item in result)
{
     Console.WriteLine(item);
}
  •  Tags:  
  • Related