none
Select from string array RRS feed

  • Question

  • I could not find a general LINQ forum to which I could post, so I am posting here.

    If I had my data in a one-column table I could use SQL like this:

    Select * From MyTable Where MyField Like 'T15-123_%'

     

    However, my data is in a string[], so what would be a LINQ query for that?

    Thanks,


    Jon Jacobs<br/> Texas in August, where lava cannot freeze

    Thursday, August 27, 2015 7:09 PM

Answers

  • To do a Linq query on an array the first thing you must do is make  the data implement the IEnumerable interface.  The easiest method is just to use the .ToList() extension.  So to do what you asked you would use Linq like

    var x = from s in theStringArray.ToList() where s.StartsWith("T15-123") select s


    Lloyd Sheen

    • Marked as answer by Jon Q Jacobs Monday, August 31, 2015 2:54 PM
    Saturday, August 29, 2015 6:15 PM

All replies

  • Hi,

    Assuming that your MyField data is an array of string, maybe you can try this code.

    Be sure to initialize "using System.Data.Linq.SqlClient;"

    //sample data
    string[] search = new string[] { "T15-123_%", "T15-124_%", "T15-125_%" };
    
                DataClasses1DataContext dc = new DataClasses1DataContext();
                foreach (string s in search)
                {
                    var x = from mytable in dc.GetTable<MyTable>()
                            //where a.MyField.StartsWith("T15-123") or
                            where SqlMethods.Like(mytable.MyField, s)
                            select mytable;
    
                    //dataGridView1.DataSource = q;
                    foreach (var row in x.ToList())
                    {
                        MessageBox.Show(row.MyField);
                    }
                }
    Hope it helps.


    Friday, August 28, 2015 2:17 AM
  • To do a Linq query on an array the first thing you must do is make  the data implement the IEnumerable interface.  The easiest method is just to use the .ToList() extension.  So to do what you asked you would use Linq like

    var x = from s in theStringArray.ToList() where s.StartsWith("T15-123") select s


    Lloyd Sheen

    • Marked as answer by Jon Q Jacobs Monday, August 31, 2015 2:54 PM
    Saturday, August 29, 2015 6:15 PM
  • Hi Jon,

    Refer here for similar samples.

    http://stackoverflow.com/questions/3913697/how-to-do-a-like-query-with-linq

    Source to Learn LINQ, MSDN Samples :

    LINQ - Sample Queries

    101 LINQ Samples

    Hope the above information helps you.

    Thanks, SMSVikasK

    Sunday, August 30, 2015 9:40 AM