List<UserInfo> users = new List<UserInfo> {
new UserInfo{UserCode=1, UserName="User001", Password="001"}, new UserInfo{UserCode=2, UserName="User002", Password="002"}, new UserInfo{UserCode=3, UserName="User003", Password="003"}, new UserInfo{UserCode=4, UserName="User004", Password="004"} }; //使用LINQ查找用户代码大于2的列表 //此时的query变量的类型是IEnumerable<UserInfo>类型 var query = from item in users where item.UserCode > 2 select item; //使用ToDictionary方法将query转换为字典类型Dictionary<int,UserInfo> userDict = query.ToDictionary(itm => itm.UserCode);Response.Write("Dictionary的结果是:");
foreach (var user in userDict) { string temp = string.Format("(Key:{0},Value:{1})", user.Key, user.Value.UserName); Response.Write(temp); }public class UserInfo
{ public UserInfo() { // //TODO: 在此处添加构造函数逻辑 // }public int UserCode { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}