1

我必须从数据表中获取两个字段。然后我应该检查一个。“listIDStr”保留不唯一的用户 ID 列表。因此,当我更新一行时,我必须使用“作为主键的 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”一起获取。有谁知道它是怎么做的?

4

2 回答 2

7

使用匿名类型,这里是 MSDN 链接

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;
于 2013-03-15T08:51:14.943 回答
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;
于 2013-03-15T09:06:59.717 回答