我在C#中非常陌生,我想在Linq.plz帮助中编写此TSql代码。谢谢
select a.Id,
a.Date,
b.Title CategoryTitle,
a.Title,
a.Description,
a.Image
from (select *,
ROW_NUMBER() over(partition by CategoryID order by Date) rankno
from News) a
join Categories b on a.CategoryID = b.Id
where rankno <= 5
答案 0 :(得分:1)
假设您有新闻和类别的枚举:
var results = News.Join(Categories, // Join News and Categories
a => a.CatergoryId,
b => b.Id,
(a,b) => new { News = a, Category = b}
)
.GroupBy(c => c.Category) // "partition by categoryId"
.SelectMany(g => g.OrderBy(gd => gd.News.CreationDate) // "order by Date"
.Take(5) // RankNo <= 5
.Select(gdd => new { // results
Id = gdd.News.Id,
Date = gdd.News.Date,
CategoryTitle = gdd.Category.Title,
Title = gdd.News.Title,
Description = gdd.News.Description,
Image = gdd.News.Image
})
);
答案 1 :(得分:0)
我使用类为您的数据库建模,以使语法正确。参见下面的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication93
{
class Program
{
static void Main(string[] args)
{
Context dbContext = new Context();
var results = (from n in dbContext.news
join c in dbContext.category.OrderBy(x => x.Date) on n.Id equals c.Id
select new { news = n, category = c})
.Select((x,i) => new { Date = x.news.Date, CategoryTitle = x.category.Title, Title = x.news.Title, Description = x.news.Description, Image = x.news.Image, RankNo = i})
.ToList();
}
}
public class Context
{
public List<News> news { get; set; }
public List<Category> category { get; set; }
}
public class News
{
public int Id { get; set; }
public DateTime Date { get; set; }
public string Title { get;set;}
public string Description { get;set;}
public byte[] Image { get;set;}
}
public class Category
{
public int Id { get; set; }
public string Title { get; set; }
public DateTime Date { get; set; }
}
}