How to find average?

  • Thread starter Thread starter Decompressor
  • Start date Start date
D

Decompressor

Guest
Hi, I have table

1613124.png

using System;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text.RegularExpressions;

namespace Fiddle
{
public class TrContext : DbContext
{

public DbSet<Main> Mains{get;set;}

protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlServer("Server = MyServer; Database=demo;Trusted_Connection=True;MultipleActiveResultSets=true");

protected override void OnModelCreating(ModelBuilder modelBuilder)
{

modelBuilder.Entity<Main>().ToTable("main");

}
}


public class Main
{
public int id { get; set; }
public DateTime calendar { get; set; }
public int weighting { get; set; }
public string goods { get; set; }
[NotMapped]
public decimal result { get; set; }
[NotMapped]
public decimal per_item { get; set; }

}
class Program
{
static void Main()
{
using(var db=new TrContext())
{


var query = db.Mains;
foreach(var z in query)
{
z.result = Regex.Matches(z.goods, @"(?i)\d+(?=\s*(items))")
.Cast<Match>().Sum(m => decimal.Parse(m.Value));
z.per_item = z.weighting/z.result;
Console.WriteLine(z.id + " " + z.calendar + " " + z.weighting+" "+z.result+" "+
String.Format("{0:n2}",z.per_item));
}
var average = query.Average(y => y.per_item);
Console.WriteLine(average);

}

}
}
}



I have result:

1613125.pngPlease,help to find average

P.S. If I make such: var average=query.Average(y=>y.per_item).ToList();

or var average=query.Average(y=>y.per_item).AsEnumerable(); I have error "decimal" does not contain a definition for "ToList()" and no accessible extension method 'ToList' accepting a first argument of type 'decimal' could be found

Continue reading...
 
Back
Top