如何将sql查询转换为linq查询
Posted
技术标签:
【中文标题】如何将sql查询转换为linq查询【英文标题】:How to transform sql query to linq query 【发布时间】:2013-06-12 11:33:12 【问题描述】:delete from detail where autoid not in (select min(autoid) from detail
where CATEGORY<>'Accepted'
group by ATM_Id, Date, Card ,Transit ,Ck)
and CATEGORY<>'Accepted'
我的尝试
var Query2 = from line in
(from line in source let fields = line.Split(',')
select new autoid = fields[0],
ATMID = fields[4],
DATE = fields[2],
CARDNo = fields[5],
TRANSIT = fields[8],
CheckNo = fields[9],
CATEGORY = fields[10],
)
orderby line.ATMID,
line.DATE,
line.CARDNo,
line.TRANSIT,
line.CheckNo ascending
where line.CATEGORY != "Accepted"
group line by new line.ATMID,
line.DATE,
line.CARDNo,
line.TRANSIT,
line.CheckNo
into gruoped
where gruoped.Count() > 1
//select autoid = gruoped.Key;
select new
//ATMID = gruoped.Key,
//DATE = gruoped.Key,
//CARDNo = gruoped.Key,
//TRANSIT = gruoped.Key,
//CheckNo = gruoped.Key,
autoid = gruoped.Key,
//CATEGORY = gruoped.Key
;
【问题讨论】:
【参考方案1】:这是一个示例,它应该如何工作,看看这个
var remove = (from aremove in db.logins
where aremove.username == userNameString
&& aremove.Password == pwdString
select aremove).FirstOrDefault();
if(remove != null)
db.logins.DeleteOnSubmit(remove);
如果您有任何问题,请随时提问!
【讨论】:
好的..但是我没有使用数据库,我的详细数据库是一个逗号分隔的文本文件,我需要从中删除重复的行...是否可以删除重复的行...谢谢 @user2448680 你应该试试你自己..如果你有问题问一个问题【参考方案2】:你可以试试这个。
var ids = (from d in detail
where d.Category != "Accepted"
group d by new d.ATM_Id, d.Date, d.Card ,d.Transit ,d.Ck into grp
select grp.Min(x => x.autoId));
var toDelete = (from d in detail
where !ids.Contains(d.AutoId) && d.Category != "Accepted"
select d);
context.DeleteOnSubmit(toDelete);
您可以只搜索所需的内容,然后重新创建逗号分隔字符串的新列表以存储回文件。
EG:
void Main()
var fields = new List<Field>
new FieldId = 1, Name = "A",
new FieldId = 1, Name = "A",
new FieldId = 2, Name = "B",
new FieldId = 1, Name = "A",
new FieldId = 3, Name = "C",
new FieldId = 2, Name = "B",
;
// Grouped
var grouped = (from f in fields
group f by new f.Id, f.Name into grp
select new Field
Id = grp.Select(x => x.Id).FirstOrDefault(),
Name = grp.Select(x => x.Name).FirstOrDefault()
);
// Makes a list of the distinct Fields
var list_Of_CSV_Items = grouped.Select(x => string.Join(",", x.Id,x.Name));
System.IO.File.WriteAllLines(@"C:\Where_your_folder_is.txt", list_Of_CSV_Items);
public class Field
public int Id get;set;
public string Name get; set;
【讨论】:
context.DeleteOnSubmit(toDelete);在这个语句给出一些错误之后......查询正文必须以 select 或 group 子句结尾.. 抱歉看到编辑,刚刚添加了select d。我使用文本编辑器来执行此操作。上下文也是您的 DataContext 所以将它交换为您的 DataContext 实例的名称。 好的..但是我没有使用DataContext,我的详细数据库是一个逗号分隔的文本文件,我需要从中删除重复的行...是否可以删除重复的行...谢谢.. 添加了一些内容供您试用并应用于您的代码。它采用独特的项目并创建一个新的逗号分隔字符串列表,供您存储回您的文件或其他内容。 谢谢我明白了......但下一个问题是,我有一个文本文件有超过 2(2000000) 行缺少行,所以它没有产生结果..但它的工作量高达 1000行...以上是关于如何将sql查询转换为linq查询的主要内容,如果未能解决你的问题,请参考以下文章
如何将此 GROUP BY / MIN SQL 查询转换为 LINQ?
如何将带有内连接的 sql 查询转换为 linq lambda 表达式?