返回行到数组
本文关键字:数组 返回 | 更新日期: 2023-09-27 18:17:29
我用c#和linq工作,我试图从一个字符串或数组中的表返回一些结果。我能够创建一个查询,查找行,但是当我试图返回列值时,我得到表列名的空数组作为我的字符串。
结果如下:
SELECT [t0].[UserID], [t0].[First], [t0].[Last], [t0].[Username], [t0].[Password], [t0].[Employee], [t0].[City], [t0].[Branch], [t0].[UserPoints], [t0].[CurrentPoints], [t0].[LastOnline], [t0].[Status] FROM [dbo].[mrobUsers] AS [t0] WHERE [t0].[Username] = @p0
这是我的Linq查询:
public string GetUserInfo(string username)
{
try
{
using (UserDataDataContext db = new UserDataDataContext())
{
var getInfo = (from row
in db.mrobUsers
where row.Username == username
select row).ToString();
return getInfo;
// I've debugged up to here, and my user name is passed into this
}
}
catch (Exception e)
{
return MySerializer.Serialize(false);
}
}
我的理想结果是:
1,Mark,Rob,mrob88, password....etc
你可以试试这个:
// You should change the return type of your method, if you want to return an array of
// strings.
public string[] GetUserInfo(string username)
{
try
{
using (UserDataDataContext db = new UserDataDataContext())
{
// Get the user's info.
var userInfo = (from row in db.mrobUsers
where row.Username == username
select row).SingleOrDefault();
// If the user's info found return the corresponding values.
if(userInfo!=null)
{
var t = typeof(userInfo);
List<string> values = new List<string>();
foreach(var prop in t.GetProperties())
{
values.Add(prop.GetValue(userInfo, null);
}
return values.ToArray();
}
else // the user's info not found and return an empty array.
{
return new string[] { };
}
// I've debugged up to here, and my user name is passed into this
}
}
catch (Exception e)
{
return MySerializer.Serialize(false);
}
}
}
但是,我建议您不要采用这种方法。我认为这将是更好的,如果你声明一个类的属性值,你想检索,像下面:
public class UserInfo
{
public int UserId { get; set; }
public string First { get; set; }
public string Last { get; set; }
// the same way you will declare the rest of your properties.
}
那么你可以把你的方法改成如下的:
public UserInfo GetUserInfo(string username)
{
try
{
using (UserDataDataContext db = new UserDataDataContext())
{
// Get the user's info.
var userInfo = (from row in db.mrobUsers
where row.Username == username
select new UserInfo
{
UserId = row.UserId,
First = row.First
Last = row.Last
}).SingleOrDefault();
return userInfo;
}
catch (Exception e)
{
return MySerializer.Serialize(false);
}
}
}