locked
How to select a distinct record when multiple records are returned in Linq to SQL RRS feed

  • Question

  • Hi

    I have a Linq to SQL query that needs to return multiple records and therefore I cannot use Distinct. However, one of the columns will have the same value for all records.

    How can I assign the value of this column to a variable without looping through the Linq resultset. Basically if the result of the Linq query was as per below;

    Col1  Col2        Col3
     Vik         Oracle
     Sam       Oracle
     Roger     Oracle

    How can I assign Col3 to a variable without looping through the Linq resultset and without using a Distinct in the Linq query.

    Vik

    Monday, November 10, 2014 7:56 AM

Answers

  • Why can't you just use a Linq projection to just make the 3rd column be a constant value?

    var artistsResult =
                    from artist in artistsDataSource
                    select new
                    {
                        Name = artist.Name,
                        NumberOfAlbums = artist.Albums.Count,

                        CompanyName = "Vic"


                    };

    • Proposed as answer by Andy ONeill Monday, November 10, 2014 6:11 PM
    • Marked as answer by Barry Wang Friday, November 28, 2014 4:36 AM
    Monday, November 10, 2014 6:09 PM

All replies

  • Something like this?

           static void Main(string[] args)
            {
                List<table> myTable = new List<table>(){
                    new table() {id = 1, name =  "Vik"},
                    new table() {id = 2, name =  "Sam"},
                    new table() {id = 3, name =  "Roger"},
                };
    
    
                myTable = myTable.AsEnumerable()
                    .Select(x => new table { id = x.id, name = x.name, type = "Oracle" }).ToList();
            }
            public class table
            {
                public int id { get; set; }
                public string name { get; set; }
                public string type { get; set; }
            }


    jdweng

    Monday, November 10, 2014 8:48 AM
  • Why can't you just use a Linq projection to just make the 3rd column be a constant value?

    var artistsResult =
                    from artist in artistsDataSource
                    select new
                    {
                        Name = artist.Name,
                        NumberOfAlbums = artist.Albums.Count,

                        CompanyName = "Vic"


                    };

    • Proposed as answer by Andy ONeill Monday, November 10, 2014 6:11 PM
    • Marked as answer by Barry Wang Friday, November 28, 2014 4:36 AM
    Monday, November 10, 2014 6:09 PM