首页 新闻 赞助 找找看

linq能否完美实现sql的row_number和like

0
悬赏园豆:10 [已解决问题] 解决于 2011-12-09 15:09

row_number能够组内排序取每组前十条,这个linq怎么实现? linq怎么实现 like ‘%a%b%’,Contains实现不了。

日暮乡关何处是的主页 日暮乡关何处是 | 初学一级 | 园豆:84
提问于:2011-11-16 17:41
< >
分享
最佳答案
1

下面的查询可以解决第一个问题:

            string[] files = 
Directory.GetFiles(@"D:\Documents\Blog");

var query = from file in files
group file by Path.GetExtension(file) into grouping
select new { Key = grouping.Key, Files = grouping.OrderBy(f => f).Take(10) };

// 遍历结果的方式
foreach (var grouping in query)
{
Console.WriteLine("Extension: " + grouping.Key);
foreach (string filename in grouping.Files)
Console.WriteLine(" - " + filename);
}

第二个问题(LINQ to SQL和EF中)必须借助于SqlMethod.Like方法:

            // 对于本地查询,要使用正则表达式来实现"%a%b%"这种匹配
string[] names = {"aaa", "abc", "ccc", "bacbc"};
var query = names
.Where(n => Regex.IsMatch(n, ".*a.*b.*")); //"%a%b%"
foreach (string n in query) Console.WriteLine(n);

//对于L2S或EF,使用SqlMethods
var query = purchases
.Where(p => SqlMethods.Like(p.Description, "%a%b%"));



 

收获园豆:6
Life a Poem | 菜鸟二级 |园豆:437 | 2011-12-09 14:18

很完美,谢谢

日暮乡关何处是 | 园豆:84 (初学一级) | 2011-12-09 15:06
其他回答(4)
0

取前10条可以用take(10)实现

乱世文章 | 园豆:147 (初学一级) | 2011-11-16 18:01

是每组前十,不是所有的前十!

支持(0) 反对(0) 日暮乡关何处是 | 园豆:84 (初学一级) | 2011-11-16 18:01

@暗夜娜姐: 都可以实现,加点园豆我给你写个示例哈^^

支持(0) 反对(0) artwl | 园豆:16736 (专家六级) | 2011-11-16 19:36
0

能啊,还有skip()方法。

悟行 | 园豆:12559 (专家六级) | 2011-11-16 18:56
0

DEMO:

class Program
{
static void Main(string[] args)
{
List<TestModel> tmList = new List<TestModel>()
{
new TestModel(){ID=1,Title="abc",type=1},
new TestModel(){ID=2,Title="bcd",type=2},
new TestModel(){ID=3,Title="acd",type=1},
new TestModel(){ID=4,Title="dca",type=3},
new TestModel(){ID=5,Title="bad",type=1},
new TestModel(){ID=6,Title="bac",type=3},
new TestModel(){ID=7,Title="cab",type=1},
new TestModel(){ID=8,Title="cba",type=2},
new TestModel(){ID=9,Title="dba",type=3},
new TestModel(){ID=10,Title="dca",type=2}
};

//like可以用下面两种方法实现
//方法一:SqlMethods.Like,只能用于操作数据库
//var tmlike=tmList.Where(t => SqlMethods.Like(t.Title,"%a%b%"));
//方法二:用Contains,StartsWith,EndsWith组合查询
var tmlike = tmList.Where(t => t.Title.Contains("c") && t.Title.Contains("b"));


//分组top实现方案:
var tmtop = tmList.GroupBy(t => t.type).Select(t => new
{
TM = t.Take(2)
});


//输出结果
Console.WriteLine("Like");
foreach (var item in tmlike)
{
Console.WriteLine(item.ID + "\t" + item.Title + "\t" + item.type);
}

Console.WriteLine("Top:");
foreach (var item in tmtop)
{
foreach (var o in item.TM)
{
Console.WriteLine(o.ID + "\t" + o.Title + "\t" + o.type);
}
Console.WriteLine();
}
Console.Read();
}
}

//测试实体
public class TestModel
{
public int ID { get; set; }
public string Title { get; set; }
public int type { get; set; }
}

输出:



收获园豆:2
artwl | 园豆:16736 (专家六级) | 2011-11-16 20:25
0

可以分字段用take(10)进行取前十

Like的用法:http://blog.sina.com.cn/s/blog_706bc7d40100plpe.html

收获园豆:2
喬喬AI | 园豆:996 (小虾三级) | 2011-11-16 21:41
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册