[英]How to calculate the average of an element in the array (salary) in C#
我還需要添加或更改什么來顯示我的 25 至 35 歲員工的工資高於平均工資。 該程序僅顯示 25 到 35 歲之間的員工。
for (int i = 0; i < employeename; i++)
{
while (br.PeekChar() != -1)
{
function[i].Name= br.ReadString();
function[i].Function= br.ReadString();
function[i].Age= br.ReadInt32();
function[i].salary= br.ReadInt32();
function[i].Studies= br.ReadString();
if ((function[i].Age>25) && (function[i].Age<35))
{
string str = String.Format("|{0,-21}|{1,-9}|{2,-7}|{3,-16}|{4,-12}|", function[i].Name, function[i].Function,
function[i].Age.ToString(), function[i].Salary.ToString(), function[i].Studies);
Console.WriteLine(str);
}
}
}
Console.ReadKey();
br.Close();
我認為您需要在過濾之前讀取所有數據並計算 avgSalary :
Map 您在員工 class 中的數據,參數為姓名、Function、年齡、薪水、學業。
var employees = new List<Employee>();
while (br.PeekChar() != -1)
{
var employee = new Employee() {
Name= br.ReadString(),
Function= br.ReadString(),
Age= br.ReadInt32(),
Salary= br.ReadInt32(),
Studies= br.ReadString()
};
employees.Add(employee);
}
var avgSalary = employees.Select(x => x.Salary).Average();
var finalList = employees.Where(x => x.Age > 25 && x.Age < 35 && x.Salary > avgSalary).ToList();
為此,您需要使用 EF & LINQ。
最好的方法是:首先讀取所有內容並添加到列表中,然后對列表進行其他操作
這是一個樣本!
sing System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
List<Employee> employees = new List<Employee>();
for (int i = 0; i < 10; i++)
{
employees.Add(new Employee
{
Name ="name "+i,
Function = "fun "+i,
Age =i+24,
Salary =100+i,
Studies ="stu"+i
});
}
//here can do any opr on list
double avg =employees.Average(s => s.Salary);
var result = employees.Where(x => x.Age > 25 && x.Age < 35 && x.Salary> avg).ToList();
foreach (var item in result)
{
Console.WriteLine("item name:" + item.Name);
}
Console.WriteLine("avg :" + avg);
Console.ReadKey();
}
public class Employee
{
public string Name { set; get; }
public string Function { set; get; }
public int Salary { set; get; }
public int Age { set; get; }
public string Studies { set; get; }
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.