再问个关于linq操作list的问题

superdesign20 2010-09-16 09:53:26
class product
{
public int id { get; set; } //注意要申明为public
public int name { get; set; }

public int score3 { get; set; }
}

class entityscroe
{
public int id { get; set; }
public int score1 { get; set; }
public int score2 { get; set; }
}

void test()
{
List<product> aproduct = new List<product>();
for (int i = 0; i < 9; i++)
{
product thp = new product();
thp.id = i;
thp.name = i + 100;
aproduct.Add(thp);
}

List<entityscroe> score = new List<entityscroe>();
for (int i = 0; i < 9; i++)
{
entityscroe thisscrore = new entityscroe();
thisscrore.id = i;
thisscrore.score1 = i + 100;
thisscrore.score2 = i + 50;
score.Add(thisscrore);
}
//结果:
List<product> listNew = (from s1 in aproduct
join s2 in score
on s1.id equals s2.id
select new product
{
id = s1.id,
score3 = s2.score1 + s2.score2
}).ToList();

}
----------------
能不能这么写,这个应该怎么写?
List<product> listNew = (from s1 in aproduct
join s2 in score
on s1.id equals s2.id
select new product
{
id = s1.id,
var temp=s2.score1 + s2.score2//这里我想定义一个临时变量,不然表达式太长了,我接下来我要做几个字段的运算,如果不弄个临时变量,就太难受了
score3 = (temp+id)/temp*id
}).ToList();
...全文
167 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
q107770540 2010-09-17
  • 打赏
  • 举报
回复
最后建议你多看书

你问的三个问题 我都有看过
都是比较基础的问题
q107770540 2010-09-17
  • 打赏
  • 举报
回复

List<product> listNew = (from s1 in aproduct
join s2 in score
on s1.id equals s2.id
select new product
{
id = s1.id,
score3 =sumScore( s2.score1 , s2.score2,s1.id)
}).ToList();

//将计算逻辑封装成方法 放在查询外边
//此处 建议你修改类 将score3改成double类型 因为除出来的结果会有小数
int sumScore(int score1, int score2,int id)
{
int result = 0;
int temp = score1 + score2;
result = (temp + id) / temp * id;
return result;
}
  • 打赏
  • 举报
回复
注意不是在select表达式里边,而是在之前,使用“let”。

自己google一下linq的语法。
  • 打赏
  • 举报
回复
类似这样:
(from s in slist
let s1 = s.Trim()
where s1 != string.Empty && !s1.StartsWith("//")
let sp = s1.Split(',')
select new G { 编号 = int.Parse(sp[0]), 隶属 = int.Parse(sp[1]), 名称 = sp[2] }).ToList();
superdesign20 2010-09-16
  • 打赏
  • 举报
回复
wuyq11,我没明白你的意思,具体点说好吗
select new product
{
id = s1.id,
temp=s2.score1 + s2.score2,
score3 = (temp+id)/temp*id
}).ToList();

目前这种写法是错误的,因为temp不是product的属性,而且也不想是他的一个属性,只是一个临时变量而已,但这里没法定义和使用,所以我想找到个正确写法
wuyq11 2010-09-16
  • 打赏
  • 举报
回复
Select操作包括9种形式,分别为简单用法、匿名类型形式、条件形式、指定类型形式、筛选形式、整形类型形式、嵌套类型形式、本地方法调用形式、Distinct形式。
wuyq11 2010-09-16
  • 打赏
  • 举报
回复
select new product
{
id = s1.id,
temp=s2.score1 + s2.score2,
score3 = (temp+id)/temp*id
}).ToList();
可调用相关方法

8,497

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 LINQ
社区管理员
  • LINQ
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧