Is there way to use Distinct in LINQ query syntax?
Is there way to rewrite:
var tbl = ds.TABLES;
var q = from c in tbl
select c.TABLE_TYPE;
string s = "";
foreach (var item in q.Distinct())
{
s += "[" + item + "]";
}
MessageBox.Sh开发者_运维问答ow(s);
So that the Distinct() call is in the LINQ query?
There is no Distinct()
method syntax in the language integrated query syntax. The closest you could do would be to move the current call:
var q = (from c in tbl
select c.TABLE_TYPE).Distinct();
The Distinct
extension method in LINQ does not have a query syntax equivalent.
See https://learn.microsoft.com/en-us/archive/blogs/charlie/linq-farm-using-distinct-and-avoiding-lambdas for additional information as to why.
(from c in tbl select c.TABLE_TYPE).Distinct();
VB has this functionality if you place the distinct after select.
You may capture HashSet and put where clause before select:
var hs = new HashSet<char>();
from c in "abcabcd"
where hs.Add(c)
select c;
In the search for a Distinct-function for LINQ upon finding this question and realizing it doesn't exist, my workaround is by using GroupBy(). The obvious problem is that the distinct-set doesn't contain all the data (say you have three fields but only want to distinct on two fields missing out on the value for the last field, but, then again, DISTINCT in t-sql works the same way).
LINQ-code (hence the Dump):
void Main()
{
var gt = new GenerateThings();
var dlist = gt.list();
dlist.Dump();
dlist.GroupBy(x => new {x.id, x.cat}).Dump();
}
public class model
{
public int id {get;set;}
public int cat {get;set;}
public int type {get;set;}
}
public class GenerateThings
{
public List<model>list()
{
var dlist = new List<model>();
dlist.Add(createNew(1, 1, 1));
dlist.Add(createNew(1, 1, 1));
dlist.Add(createNew(1, 2, 1));
dlist.Add(createNew(1, 2, 1));
dlist.Add(createNew(1, 1, 2));
dlist.Add(createNew(1, 1, 2));
dlist.Add(createNew(1, 1, 2));
return dlist;
}
private model createNew(int id, int cat, int type){
return new model{
id = id,
cat = cat,
type = type
};
}
}
LINQ-dump result
精彩评论