Mandar Jogalekar
Mandar Jogalekar

Reputation: 3281

Linq select from database table where matching property from List

I have a List with records of following class which is something like this

  public class TestRecord
  {
     public int RecordsId{get;set;}
public string Name{get;set;}
-- and more such properties.

  }

Now I have database table which I access from linq which contains RecordId column , values which will match RecordId value from above List.

  var result=from p in _context.Details

however I am thinking I could do where/ contains on this linq query and provide it with a clause to match RecordId from a list

 List<TestRecord> records -- this has let's say 100 records.

Doing simply this does not work as linq can't join with generic List

    var finalresult = from p in context.details
                      join a in records on p.recordId equals a.recordId

Any solutions for this using Linq?

Upvotes: 1

Views: 3539

Answers (4)

rkn53940
rkn53940

Reputation: 51

i got a solution in vb.net. I guess it will no problem for you to translate.

My Class TestRecord:

Public Class TestRecord
Private _RecordsID As Integer
Private _Name As String
Public Property RecordsID As Integer
    Get
        Return _RecordsID
    End Get
    Set(value As Integer)
        _RecordsID = value
    End Set

End Property
Public Property Name As String
    Get
        Return _Name
    End Get
    Set(value As String)
        _Name = value
    End Set

End Property

End Class

Then, your main Sub (or anything else)

   Dim records As New List(Of TestRecord)
    Dim context As New DataTable()
    context.Columns.Add("DataTableRecordID")
    context.Columns.Add("Name")
    For i As Integer = 0 To 100
        records.Add(New TestRecord With {
            .RecordsID = i,
            .Name = "TestUser" & i.ToString()})


        context.Rows.Add(i, "TestUser" & i.ToString())
    Next


    Dim FinalResult = From p In context.AsEnumerable()
                      Join a In records.AsEnumerable() On p.Field(Of String)("DataTableRecordID") Equals a.RecordsID

I got a little loop at the beginning to create some datarows and a datatable. I guess you use datatable (or Dataset) in your "context" => context.details example.

In the linq query, you can you set your field in the datatable and the generic list (TestRecord) will give you the needed column (a.RecordID) from itself.

Sry for my bad english x)

Upvotes: 1

TriV
TriV

Reputation: 5148

You can use Any like this:

var finalresult = context.details.Where(d => records.Any(r=>r.recordId == d.recordId));

Upvotes: 1

Chetan
Chetan

Reputation: 6911

 var s = from p in tests where names.Contains(p.Name) select p;

Upvotes: 0

Rahul
Rahul

Reputation: 77896

You can use Contains() like

var finalresult = context.details.Where(d => records.Contains(d.recordId));

Upvotes: 1

Related Questions