Solved

LINQ Query: Multiple "StartsWith"

Posted on 2011-03-15
5
1,832 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
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.
In this video, viewers will be given step by step instructions on adjusting mouse, pointer and cursor visibility in Microsoft Windows 10. The video seeks to educate those who are struggling with the new Windows 10 Graphical User Interface. Change Cu…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …

630 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