如何简化代码?
isMe 改成这样,看行不?
isMe = ((user==null)?false:(user.UId==c.UId))
请问你的.Net Framework 是哪个版本?我写了个 demo 怎么没问题:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) {
}
private void Form1_Load(object sender, EventArgs e) {
BuilCommentList(null, 0);
}
public List<CommentForPictureDetail> BuilCommentList(UserForIndex user, int pId) {
List<Comment> comments = new List<Comment>();
comments.AddRange(new Comment[]{
new Comment(){
CId = 1,
UId = 1,
Content = "hello",
UserInfo = new UserInfo{UId = 1, UserName = "tom"},
PostDate = DateTime.Now
},
new Comment(){
CId = 2,
UId = 1,
Content = "world",
UserInfo = new UserInfo{UId = 1, UserName = "alice"},
PostDate = DateTime.Now
}
});
List<CommentForPictureDetail> cList = new List<CommentForPictureDetail>();
cList = comments.Select(c => new CommentForPictureDetail() {
cId = c.CId,
cUId = c.UId,
content = c.Content,
isMe = ((user == null) ? false : (user.UId == c.UId)),
username = c.UserInfo.UserName,
postDate = c.PostDate
}).ToList();
return cList;
}
}
public class UserForIndex {
public int UId {
get;
set;
}
}
public class CommentForPictureDetail {
public int cId {
get;
set;
}
public int cUId {
get;
set;
}
public string content {
get;
set;
}
public bool isMe {
get;
set;
}
public string username {
get;
set;
}
public DateTime postDate {
get;
set;
}
}
public class Comment {
public int CId {
get;
set;
}
public int UId {
get;
set;
}
public string Content {
get;
set;
}
public UserInfo UserInfo {
get;
set;
}
public DateTime PostDate {
get;
set;
}
}
public class UserInfo {
public int UId {
get;
set;
}
public string UserName {
get;
set;
}
}
哈哈哈哈我终于懂了,这里要用动态的方式构造Lambda,就是一直创建Expression类的方式造一个lambda表达式
int? userid = user == null ? null : user.userid;
…
isme = uid == userid,