猿问

如果值是字符串类型,则按片段搜索,但如果值是 int,则按和整个搜索

我决定用 C# 创建一个简单的 MVVM 应用程序。我有一个用户集合。我可以编辑它们、添加、删除、更新和搜索。对于最后一个选项,我遇到了问题。以下是部分有问题的代码:


var Usersview = new ObservableCollection<User>

                (from item in Users

                 where (

                Convert.ToString(item.UserId) == (Names[0])

                && item.FirstName.Contains(Names[1])

                && item.LastName.Contains(Names[2])

                && item.City.Contains(Names[3])

                && item.State.Contains(Names[4])

                && item.Country.Contains(Names[5]))

                select item);

名称是我可以搜索的值数组。名称可以为空。只有 UserID 是 int,其余都是 string。


我想要实现的是按字符串类型名称的片段进行搜索,但是如果设置了 UserID 值,则程序必须按整个 int(而不是其片段)进行搜索。如果 Names[0] 是 string.Empty,则程序不会搜索任何内容。你可以帮帮我吗?但要记住。这是我使用 MVVM 和 Linq 的第一步。所以请原谅。


PIPIONE
浏览 173回答 1
1回答

潇湘沐

据推测,不必为搜索填写所有搜索字段。此外,您不应该将 an 转换int为 astring来比较相等性。重命名您的范围变量和搜索条件以使其更有意义,我得到:var Usersview = new ObservableCollection<User>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (from user in Users&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;where&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(String.IsNullOrEmpty(searchCriteria[0]) || Convert.ToInt32(searchCriteria[0]) == user.UserId) &&&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(String.IsNullOrEmpty(searchCriteria[1]) || user.FirstName.Contains(searchCriteria[1])) &&&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(String.IsNullOrEmpty(searchCriteria[2]) || user.LastName.Contains(searchCriteria[2]) &&&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(String.IsNullOrEmpty(searchCriteria[3]) || user.City.Contains(searchCriteria[3])) &&&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(String.IsNullOrEmpty(searchCriteria[4]) || user.State.Contains(searchCriteria[4])) &&&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(String.IsNullOrEmpty(searchCriteria[5]) || user.Country.Contains(searchCriteria[5]))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; select user);
随时随地看视频慕课网APP
我要回答