LINQ select distinct c#

前端 未结 3 965
悲哀的现实
悲哀的现实 2021-01-02 21:11

I\'m trying to do a query that does not include repeated IdUser values, ​​but does not work.

this is my linq query:

var         


        
3条回答
  •  一生所求
    2021-01-02 21:30

    Note: The following can be run in LinqPad (free at http://www.linqpad.net/) - simply set the Language dropdown to "C# Program" and paste the code into the editor window.

    You can use "group" to provide your distinct requirement as follows:

    void Main()
    {
        var db = new DataBase();
        var sql= (from u in db.USER
              join c in db.CONSULT on u.IdUser equals c.IdUser 
              group c by new { c.IdUser, c.DateCreate, c.IdTypeConsult, u.Sex } into gc
              select new UsuersViewModel 
                     {  
                        IdUser = gc.Key.IdUser, 
                        DateCreate=gc.Key.DateCreate, 
                        IdTypeConsult = gc.Key.IdTypeConsult, 
                        Sex=gc.Key.Sex 
                     })
                     .Distinct();
        sql.Dump("SQL Distinct Demo");
    }
    public class Consultation {
        public int  IdUser {get;set;}
        public DateTime DateCreate {get;set;}
        public int IdTypeConsult {get;set;}
    }
    public class UsuersViewModel : Consultation {
        public string Sex {get;set;}
    }
    public class DataBase {
        public IEnumerable CONSULT {
            get { 
                return new List{
                    new Consultation { IdUser = 1, DateCreate=DateTime.Today, IdTypeConsult = 2},
                    new Consultation { IdUser = 2, DateCreate=DateTime.Today.AddDays(1), IdTypeConsult = 4}
                };
            }}
        public IEnumerable USER {
            get {
                return new List{
                    new UsuersViewModel { IdUser = 1, Sex="M"},
                    new UsuersViewModel { IdUser = 1, Sex="M"},
                    new UsuersViewModel { IdUser = 2, Sex="F"},
                    new UsuersViewModel { IdUser = 2, Sex="F"}
                };
            }}
    }
    

    The following is the result:

提交回复
热议问题