Solved

LINQ Query: Multiple "StartsWith"

Posted on 2011-03-15
5
1,652 Views
Last Modified: 2012-05-11
Briefly:
      string[] myarray = { "banana", "apple", "badminton","sansa stark" };
      string[] lookup = {"a", "ban"};
      string[] query = ???;

How do I use "lookup" as a "StartsWith" filter?  Query should return "apple" and "banana".  Both method-based and the verbose version would be greatly appreciated...
0
Comment
Question by:tknudsen-qec
  • 2
  • 2
5 Comments
 
LVL 53

Expert Comment

by:Dhaest
ID: 35138647
Below you can find an example with a list of strings (which is in my eyes a better solution)
public static class StringExtensions 
    { 
        public static bool StartsWithAny(this string s, IEnumerable<string> items) 
        { return items.Any(i => s.StartsWith(i)); 
        } 
    } 

   public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            List<string> myarray = new List<string>() { "banana", "apple", "badminton", "sansa stark" };
            List<string> lookup = new List<string>{"a", "ban"};
            var query = from x in myarray where x.StartsWithAny(lookup) select x;
            foreach (string x in query)
            {
                MessageBox.Show (x);
            }
        }

}

Open in new window

0
 
LVL 53

Expert Comment

by:Dhaest
ID: 35138660
Added a small example how you can easily transform your string[] into list<string> and use the same query
public static class StringExtensions 
    { 
        public static bool StartsWithAny(this string s, IEnumerable<string> items) 
        { return items.Any(i => s.StartsWith(i)); 
        } 
    } 


        private void Form1_Load(object sender, EventArgs e)
        {

            string[] myList = { "banana", "apple", "badminton","sansa stark" };
            string[] lookupList = {"a", "ban"};


            List<string> StringtoList = new List<string>(myList.Length);//AddRange is a method of List<T> objects that enables the conversion.//We just need to pass the reference to the array.            
            StringtoList.AddRange(myList);

            List<string> LookuptoList = new List<string>(lookupList.Length);//AddRange is a method of List<T> objects that enables the conversion.//We just need to pass the reference to the array.            
            LookuptoList.AddRange(lookupList);

            query = from x in myarray where x.StartsWithAny(lookup) select x;
}

}

Open in new window

0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 35138832
Here's my offering:
string[] queryResult = myarray.Where(item => lookup.Any(l => item.StartsWith(l))).ToArray();

Open in new window

0
 
LVL 3

Author Closing Comment

by:tknudsen-qec
ID: 35138967
kaufmed: works great and is clean.  Thanks kindly.

I couldn't get prior solution to work although at a glance I think it just needed a bit of cleaning up and a refresher on method extensions.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 35139211
NP. Glad to help  : )
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now