在跨平台 xamarin 项目(ios 和 android)中使用 c# 从查询列表检索数据时面临参数异常错误。我正在尝试从天蓝色(云)上的简单表检索数据。这是我的代码
try
{
var client = new MobileServiceClient("https://eg.azurewebsites.net");
IMobileServiceTable<Reg> regTable = client.GetTable<Reg>();
Reg reg = new Reg();
string imail = uemail2.Text.ToString();
// This query to seach email
var email1 = await regTable
.Where(Reg => Reg.email.ToString() == imail)
.Select(email => email.Text.ToString())
.ToListAsync();
notice3.Text = email1[0].ToString();
}
catch (ArgumentException ex)
{
notice.Text = "Arguments Error" + ex.Message + ex.StackTrace + ex.HelpLink + ex.Source;
}
错误详情
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index at System.ThrowHelper.ThrowArgumentOutofRange_IndexException.... ...//continued ex.Source = mscorlib
提前致谢
我更新的查询:
public async Task<ObservableCollection<Reg>> GetTodoItemsAsync(bool syncItems = false)
{
var client = new MobileServiceClient("https://eg.azurewebsites.net");
IMobileServiceTable<Reg> regTable = client.GetTable<Reg>();
Reg reg = new Reg();
string imail= uemail2.Text.ToString();
IEnumerable<Reg> items = await regTable
.Where(email=> email.Text.ToString() == imail)
.ToEnumerableAsync();
return new ObservableCollection<Reg>(items);
}
private async void v_OnClicked(object sender, EventArgs e)
{
var client = new MobileServiceClient("https://eg.azurewebsites.net");
IMobileServiceTable<Reg> regTable = client.GetTable<Reg>();
Reg reg = new Reg();
string imail = uemail2.Text.ToString();
await GetTodoItemsAsync();
items email3 = new items();
vnotice2.Text = email3.ToString();
}
最佳答案
email1
似乎是空的,因此它无法在列表中找到第一个元素并导致索引异常。
您应该在访问该列表的任何元素之前验证该列表。
if(email1.Count > 0)
notice3.Text = email1[0].ToString();
得到空 email1 的可能原因,可能是 where 子句中的字符串比较,您应该忽略大小写并比较字符串,除非您确定比较的两个参数具有相同的大小写。此外,如果您只想获取一封电子邮件,那么您应该使用 FirstOrDefaultAsync。修改后的查询如下所示。
notice3.Text = await regTable
.Where(Reg => Reg.email.Equals(imail, StringComparison.OrdinalIgnoreCase))
.Select(email => email.Text.ToString()).FirstOrDefaultAsync<string>()
关于c# - 在跨平台 xamarin 项目(ios 和 android)中使用 c# 从查询列表中检索数据时遇到参数异常错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51181258/