【问题标题】:Querying the id of an entity using linq使用 linq 查询实体的 id
【发布时间】:2013-05-14 07:30:39
【问题描述】:

在以下方法中,我尝试通过传递 id 值来获取用户名,其中作为参数传递的 id 可以是 csv 中的多个值(例如:1,2),并作为 IEnumerable 返回给调用函数。

代码如下:

[NonAction]
public static IEnumerable<UserProfile> SearchCMSAdmins(string s)
{
    //var searchResults = Entities.UserProfiles.Where(item =>item.UserName.Contains(s));
    //return searchResults;

    string[] ids = s.Split(',');

    IEnumerable<UserProfile> results = null;
    IList<UserProfile> user = new List<UserProfile>();

    for (int i = 0; i < ids.Length; i++)
    {
        int id = Convert.ToInt32(ids[i].ToString());
        var entity = Entities.UserProfiles.Where(item => item.UserId);
        //user.Add(entity);
        results = results.Concat(entity);
    }

    return results;
}

感谢任何帮助。

【问题讨论】:

  • 你应该不需要 ids[i] --> .ToString();,ids 已经是字符串了,你的意思是 Entities.UserProfiles.Where(item => item.UserId == i ) ?

标签: c# .net linq querying


【解决方案1】:

尝试使用Contains

var results = Entities.UserProfiles.Where(item => ids.Contains(item.UserId));

http://msdn.microsoft.com/en-us/library/ms132407.aspx

【讨论】:

    【解决方案2】:

    您可以将id 数组设为int 类型,您可以使用int.TryParseConvert.ToInt32 之类的:

    int[] ids = s.Split(',').Select(r=> Convert.ToInt32(r)).ToArray();
    

    稍后您可以将 LINQ 查询修改为:

    IList<UserProfile> user = Entities.UserProfiles
                                      .Where(item=> ids.Contains(item)).ToList();
    

    这就像Select * from table where ID in (1,2,3)Creating IN Queries With Linq to SQL 的想法

    【讨论】:

      【解决方案3】:
      [NonAction]
      public static IEnumerable<UserProfile> SearchCMSAdmins(string s)
      {
          string[] ids = s.Split(',');
      
          foreach (string idAsString in ids)
          {
              int id = Convert.ToInt32(idAsString);
              var entity = Entities.UserProfiles.Where(item => item.UserId == id);
              yield return entity;
          }
      }
      

      应该这样做(也应该有一些验证代码,以防 id 不是 int 或实体为 null)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-21
        • 2021-12-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多