Solved

LINQ Query: Multiple "StartsWith"

Posted on 2011-03-15
5
1,611 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 74

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 74

Expert Comment

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

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

760 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

25 Experts available now in Live!

Get 1:1 Help Now