我必须从datatable获得两个字段。然后我应该检查一个。 “listIDStr”保留不是唯一的userID列表。所以我必须使用“当我更新行时ID是主键。
List<string> listIDStr = new List<string>();
...
var sqlData = SqlDataBase.SqlGetTable("SELECT ID,UserID FROM TBL_UserT WHERE SID = " + 4663 + " AND UserID = '" + UserID + "'")
.AsEnumerable()
.ToList()
.ConvertAll(x=>x.Field<string>("UserID"))
.ToList();
List<string> Cikan = sqlData.Where(x => !listIDStr.Contains(x)).ToList();
List<string> Eklenen = listIDStr.Where(x => !sqlData.Contains(x)).ToList();
以上代码是针对一个字段运行的。但我想将“ID”与“UserID”一起使用。有没有人知道它是怎么做的?
答案 0 :(得分:7)
使用匿名类型here is the MSDN link。
var dtEnumerable = SqlDataBase.SqlGetTable("SELECT ID,UserID FROM TBL_UserT WHERE SID = " + 4663 + " AND UserID = '" + UserID + "'").AsEnumerable().ToList();
var newVariable = dtEnumerable.Select(x => new { UserID = x.Field<string>("UserID"), ID = x.Field<string>("ID") });
//Get new/old
var states = newVariable.Select(x => new { IsNew = !listIDStr.Contains(x.UserId), IsUpdate = listIDSTr.Contains(x.UserID), ID = x.UserID });
var updates = states.Where(x => x.IsUpdate).Select(x => x.UserID);
var newIds = states.Where(x => x.IsNew).Select(x => x.UserID);
//We now have access to both!
string firstUserID = newVariable.First().UserID;
string firstID = newVariable.First().ID;
答案 1 :(得分:0)
基本上,您希望将数据“投影”回到不同类型的对象中,如果您不打算将其传递到方法之外,则可能甚至是匿名对象。
匿名对象
var user = SqlDataBase.SqlGetTable("select Id, Name from User where ...")
.AsEnumerable()
.ToList()
.Select(x => new { x.Id, x.Name })
.SingleOrDefault();
int userId = user.Id;
string username = user.Name;
强类型对象
var user = SqlDataBase.SqlGetTable("select Id, Name from User where ...")
.AsEnumerable()
.ToList()
.Select(x => new UserViewModel { Id = x.Id, Name = x.Name })
.SingleOrDefault();
int userId = user.Id;
string username = user.Name;