c# - 在跨平台 xamarin 项目(ios 和 android)中使用 c# 从查询列表中检索数据时遇到参数异常错误

标签 c# android ios list xamarin

在跨平台 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/

相关文章:

c# - 如何使用 JSON.net 将枚举序列化为空值

Android 编辑文本 : How to create an empty bullet paragraph by BulletSpan?

ios - UILabel 高度不变

c# - 如何在 WPF C# 中获取 treeviewitem 的级别?

c# - 与在 Visual Studio 中运行相比,WPF exe 运行速度非常慢

c# - 如何在本地测试 Azure 队列触发器函数?

Android studio 按钮没有做任何事情真的很困惑

android - 在 Android 中支持新的蓝牙设备

ios - 在 Xcode 模拟器中将 View 堆栈压缩到一个 block 中

ios - 在应用程序中添加 Fabric 时,链接器命令失败,退出代码为 1(使用 -v 查看调用)