Search code examples
c#xamarin.formsandroid-sqlitesqlite-net

How do I Sum a List from SQLite database


I'm trying to print the sum of the score numbers from the database to Label, but I can't get it up and running.

I use Entry as input for the score and names and then a button function to store them into the tables in the database. It looks something like this:

public void Next_round(object sender, System.EventArgs e)
        {
            Score score = new Score()
            {
                score1 = scoreEntry1.Text,
                score2 = scoreEntry2.Text
            };

            using (SQLiteConnection conn = new SQLiteConnection(App.FilePath))
            {
                conn.CreateTable<Score>();
                conn.Insert(score);
            }
        } 

tables

using System;
using SQLite;

namespace App1.Classes
{
    [Table("Player")]
    public class Player
    {
        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }

        public string pName1 { get; set; }

        public string pName2 { get; set; }

    }
    [Table("Score")]
    public class Score
    {
        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }
        public string score1 { get; set; }
        public string score2 { get; set; }
    }
}

XAML page

<ListView x:Name="playersListView">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Grid>
                            <Label Grid.Column="0" Grid.Row="0" Text="{Binding pName1}" /FontAttributes="Bold" /> //Here is the players name
                            <Label Grid.Column="0" Grid.Row="0" Text="{Binding pScore1}" /> //And here's his score
                            

                            <Label Grid.Column="1" Grid.Row="0" Text="{Binding pName2}" FontAttributes="Bold" />
                            <Label Grid.Column="1" Grid.Row="0" Text="{Binding pScore2}"/>
                            
                        </Grid>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        <Label x:Name="fScore1" /> //here should be the sum

I've tried to put the database into a list using .ToList() and then put it into another for the .Sum() method to work, but it didn't work

.cs file

namespace App1
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Page4 : ContentPage
    {
        public Page4()
        {
            InitializeComponent();
            
        }
        private void Reset(object sender, EventArgs e)
        {
            App.Current.MainPage = new NavigationPage(new MainPage());
        }
        protected override void OnAppearing()
        {
            base.OnAppearing();

            using (SQLiteConnection conn = new SQLiteConnection(App.FilePath))
            {
                conn.CreateTable<Player>();
                var players = conn.Table<Player>().ToList();
                conn.CreateTable<Score>();
                List<Score> scores = conn.Table<Score>().ToList();

                List<int> list = new List<int>();
                list.AddRange((IEnumerable<int>)scores);//here i tried adding it into another table 
but it throws an exception "System.InvalidCastException: 'Specified cast is not valid.'"

                string res = list.Sum().ToString();

                fScore1.Text = res;
                playersListView.ItemsSource = players;
            }
        }
    }
}

If anyone could help me, I would be very grateful


Solution

  • List<int> list = new List<int>();
    list.AddRange((IEnumerable<int>)scores);
    

    Since the type of scores is List<Score> scores ,so you can't convert scores into type List<int> directly.

    If you want to calculate the sum of every score1 in list scores,you can go through scores, and get score1 of each item.

    Please refer to the following code:

            List<Score> scores = conn.Table<Score>().ToList();
            
            int score1_sum = 0 ;
            foreach (Score score in scores) {
               score1_sum +=  Int16.Parse(score.score1);
              }
    
            fScore1.Text = score1_sum.ToString();