Is there way to use Distinct in LINQ query syntax?

前端 未结 6 2046
余生分开走
余生分开走 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: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 Listlist()
        {
            var dlist = new List();
            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

提交回复
热议问题