开发者

LINQ to SQL omit field from results while still including it in the where clause

Basically I'm trying to do this in LINQ to SQL;

SELECT DISTINCT a,b,c FROM table WHERE z=35

I have tried this, (c# code)

(from record in db.table
select new table {
    a = record.a,
    b = record.b,
    c = record.c
}).Where(record => re开发者_StackOverflow社区cord.z.Equals(35)).Distinct();

But when I remove column z from the table object in that fashion I get the following exception;

Binding error: Member 'table.z' not found in projection.

I can't return field z because it will render my distinct useless. Any help is appreciated, thanks.

Edit:

This is a more comprehensive example that includes the use of PredicateBuilder,

var clause = PredicateBuilder.False<User>();
clause = clause.Or(user => user.z.Equals(35));
foreach (int i in IntegerList) {
    int tmp = i;
    clause = clause.Or(user => user.a.Equals(tmp));
}

var results = (from u in db.Users
               select new User {
                   a = user.a,
                   b = user.b,
                   c = user.c
               }).Where(clause).Distinct();

Edit2:

Many thanks to everyone for the comments and answers, this is the solution I ended up with,

var clause = PredicateBuilder.False<User>();
clause = clause.Or(user => user.z.Equals(35));
foreach (int i in IntegerList) {
    int tmp = i;
    clause = clause.Or(user => user.a.Equals(tmp));
}

var results = (from u in db.Users
               select u)
               .Where(clause)
               .Select(u => new User {
                   a = user.a,
                   b = user.b,
                   c = user.c
               }).Distinct();

The ordering of the Where followed by the Select is vital.


problem is there because you where clause is outside linq query and you are applying the where clause on the new anonymous datatype thats y it causing error

Suggest you to change you query like

(from record in db.table
where record.z == 35
select new table {
    a = record.a,
    b = record.b,
    c = record.c
}).Distinct();


Can't you just put the WHERE clause in the LINQ?

(from record in db.table
where record.z == 35
select new table {
    a = record.a,
    b = record.b,
    c = record.c
}).Distinct();

Alternatively, if you absolutely had to have it the way you wrote it, use .Select

.Select(r => new { a = r.a, b=r.b, c=r.c }).Distinct();

As shown here LINQ Select Distinct with Anonymous Types, this method will work since it compares all public properties of anonymous types.

Hopefully this helps, unfortunately I have not much experience with LINQ so my answer is limited in expertise.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜