Is there way to use Distinct in LINQ query syntax?

前端 未结 6 2047
余生分开走
余生分开走 2021-01-01 08:10

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          


        
相关标签:
6条回答
  • 2021-01-01 08:43

    The Distinct extension method in LINQ does not have a query syntax equivalent.

    See https://docs.microsoft.com/en-us/archive/blogs/charlie/linq-farm-using-distinct-and-avoiding-lambdas for additional information as to why.

    0 讨论(0)
  • 2021-01-01 08:45

    VB has this functionality if you place the distinct after select.

    0 讨论(0)
  • 2021-01-01 08:49
    (from c in tbl select c.TABLE_TYPE).Distinct();
    
    0 讨论(0)
  • 2021-01-01 08:49

    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;
    
    0 讨论(0)
  • 2021-01-01 08:50

    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

    0 讨论(0)
  • 2021-01-01 09:00

    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();
    
    0 讨论(0)
提交回复
热议问题