C#数组分组_C#数据分组_C# Linq分组使用整理
一、C# 数组分组,数据分组--自己写算法处理
1.数字数组分组
//[1,3,5,3,5,7,8,5,1,1]
//1,3,5,7,8
//3,1,3,1,1
/// <summary>
/// 使用 循环,自己分组---》语言的基础逻辑,基础算反
/// </summary>
public static void Test1()
{
int[] numbers = new int[] { 1,5, 3, 5, 7, 8, 5, 1, 1 };
//1.去重复
List<int> tempList = new List<int>();
foreach (var item in numbers)
{
if (!isExists(item)) {
tempList.Add(item);
}
}
//2.算个数
foreach (var item in tempList)
{
Console.WriteLine($"{item}---总共{getCount(item)}个");
}
//判断数字在数组中是否已经存在
bool isExists(int num) {
for (int i = 0; i < tempList.Count; i++)
{
var item = tempList[i];
if (item == num)
return true;
}
return false;
}
//找个数
int getCount(int num)
{
int count = 0;
foreach (var item in numbers)
{
if (item == num)
count++;
}
return count;
}
}
2.对象数组分组
/// <summary>
/// 对象数组分组
/// </summary>
public static void Test2()
{
List<Student> stuList = new List<Student>() {
new Student(){ Name="张三",ClassName="1班"},
new Student(){ Name="李四",ClassName="1班"},
new Student(){ Name="王五",ClassName="2班"},
new Student(){ Name="赵六",ClassName="2班"},
new Student(){ Name="憋气",ClassName="2班"},
};
//1.去重复,找班级
List<string> classList = new List<string>();
foreach (var item in stuList)
{
if (!isExists(item.ClassName))
{
classList.Add(item.ClassName);
}
}
//2.展示班级+数量+ 学生列表
foreach (var item in classList)
{
Console.WriteLine($"【{item}】---学生数量:{getCount(item)} ----学生列表:{getStuList(item).ToJsonString()}");
}
bool isExists(string classname)
{
foreach (var item in classList)
{
if (item == classname)
return true;
}
return false;
}
int getCount(string classname)
{
int count = 0;
foreach (var item in stuList)
{
if (item.ClassName == classname)
{
count++;
}
}
return count;
}
List<Student> getStuList(string classname)
{
List<Student> temp = new List<Student>();
foreach (var item in stuList)
{
if (item.ClassName == classname)
{
temp.Add(item);
}
}
return temp;
}
}
public class Student
{
public string Name { get; set; } //学生姓名
public string ClassName { get; set; }//学生班级
}
二、C# Linq数据分组(推荐使用)
1.简单数字分组
//简单数字分组
int[] numbers = new int[] { 1, 5, 3, 5, 7, 8, 5, 1, 1 };
var tempList = numbers.GroupBy(q => q);
foreach (var item in tempList)
{
Console.WriteLine($"{item.Key}---总共{item.Count()}个");
}
2.对象数组分组
//对象的逻辑字段分组
List<Student> stuList = new List<Student>() {
new Student(){ Name="张三",ClassName="1班"},
new Student(){ Name="李四",ClassName="1班"},
new Student(){ Name="王五",ClassName="2班"},
new Student(){ Name="赵六",ClassName="2班"},
new Student(){ Name="憋气",ClassName="2班"},
};
var tempStuList = stuList.GroupBy(q => q.ClassName);
foreach (var item in tempStuList)
{
Console.WriteLine($"【{item.Key}】---学生数量:{item.Count()} ----学生列表:{stuList.Where(q => q.ClassName == item.Key).ToJsonString()}");
}
3.组合数据分组
//组合分组,new一个匿名对象即可
query.GroupBy(q => new { q.Year, q.Month })
.Select(q => new
{
Year = q.Key.Year,
Month = q.Key.Month,
BuildAmount = q.Sum(i => i.BuildAmount),
RecAmount = q.Sum(i => i.RecAmount),
Amount = q.Sum(i => i.Amount),
RealAmount = q.Sum(i => i.RealAmount)
});
更多: