【问题标题】:IQueryable OrderBy/GroupBy RegexIQueryable OrderBy/GroupBy 正则表达式
【发布时间】:2014-07-03 17:16:23
【问题描述】:

我有一个 IQueryable 结果,其名称如下所示:

100lbs
10pts
150lbs
11pts
15pt
10pt

我想按尾随字母对结果进行分组,这样结果看起来更像这样:

100lbs
150lbs
10pt
15pt
10pts
11pts

是否可能/我如何使用正则表达式来完成此操作?

【问题讨论】:

  • IQuerable 提供程序是什么?我怀疑 EF / NHibernate 会支持那么复杂的东西。
  • 需要更多信息。您的 IQuerable 在内存中 (Linq2Objects) 还是来自 LinqToSQL 或 LinqToEntities?
  • 您还应该考虑将10lbs 放在不同的列中。
  • 它的 Linq-to-Entities。我同意单独的列会是更好的设计,不幸的是我继承了这一点。

标签: c# regex split group-by iqueryable


【解决方案1】:

我不知道您的 linq 语句是什么样的,但您可以尝试创建一个假变量,仅用于排序

有点像

var result =
    (from c in db.Table 
     select new 
     {
         mainresult = c.mainresult, 
         tempresult ==c.mainresult,

     }
    ).ToList().Select(c=>new{
      mainresult = c.mainresult, 
      tempresult=new string(c.mainresult
             .Where(!char.IsDigit).ToArray())})
    .OrderBy(c=>c.tempresult)
    .Select(c=>c.mainresult)
    .ToList();

【讨论】:

  • 你不能这样做.Where(!char.IsDigit)
  • 为什么因为它可查询?
  • 因为Operator ! cannot be applied to operand of type 'method group'。你想要.Where(x => !char.IsDigit(x))
  • @gunr2171 当然可能无法被查询提供者理解,即使该更改使其编译。
【解决方案2】:
var list = new List<string>();
            list.Add("100lbs");
            list.Add("10lbs");
            list.Add("10pts");

            var groupings = list.GroupBy((s)=>{
                if (s.EndsWith("lbs"))//you can use regex here 
                {
                    return "lbs";
                }
                else if (s.EndsWith("lbs"))
                {
                    return "pts";
                }
                return "none";
            },s=>s);
            foreach (var item in groupings)
            {
                item.key will have category "lbs"/"pts" 
            }

【讨论】:

  • 请记住,这很可能需要来自数据库,这意味着查询是从实体框架或 NHibernate 运行的。 sql知道EndsWith是什么吗?
  • 我希望这能让你开始。使用正则表达式代替 EndsWith。您可以将结果放入单独的列表中,然后进行处理,是的,EF/Nhibernate 也不知道 EndsWith 或正则表达式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多