【问题标题】:C# Linq Select Rows Where ID Equals ID in CSVC# Linq 在 CSV 中选择 ID 等于 ID 的行
【发布时间】:2013-04-03 19:36:10
【问题描述】:

我拥有的是从查询字符串(例如 23、51、6、87、29)接收到的一串逗号分隔的 ID。或者,该字符串可以只说“全部”。

在我的 Linq 查询中,我需要一种说法(在伪代码中):

from l in List<>
    where l.Id = all_of_the_ids_in_csv
    && other conditions
select new {...}

我只是不知道该怎么做。我什至不确定用谷歌搜索什么来让我朝着正确的方向前进。任何指向正确方向的方法都会非常有帮助。

【问题讨论】:

    标签: c# sql-server linq csv


    【解决方案1】:

    我建议将您的查询分成两部分 - 第一部分将按 ID 选择,而选择的部分将选择 其他条件

    首先:检查查询字符串是否包含数字,或者只是all

    var IEnumerable<ListItemType> query = sourceList;
    
    if(queryStringValue != "All")
    {
        var ids = queryStringValue.Split(new[] { ',' })
                                  .Select(x => int.Parse(x)) // remove that line id item.Id is a string
                                  .ToArray();
    
        query = query.Where(item => ids.Contains(item.Id));
    }
    
    from l in query
        // other conditions
    select new {...}
    

    由于 LINQ 查询延迟执行,您可以构建这样的查询而不会降低性能。在您请求结果之前不会执行查询(通过ToList 调用或枚举)。

    【讨论】:

    • 太完美了!正是我需要的。谢谢!
    【解决方案2】:

    如果您真的只需要一个 LINQ 查询:

    var idArray = all_of_the_ids_in_csv.Split(',');
    from l in List<>
        where (all_of_the_ids_in_csv == "All" || idArray.Contains(l.Id))
        && other conditions
    select new {...}
    

    【讨论】:

      【解决方案3】:

      诀窍是使用string.Split

      var ids = string.split(rawIdString, ",").ToList();
      var objects = ids.Where(id=> /*filter id here */).Select(id=>new { /* id will be the single id from the csv */ }); 
      // at this point objects will be an IEnumerable<T> where T is whatever type you created in the new statement above
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-19
        • 2011-12-10
        • 2023-03-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多