CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    May 2013

    linq on two string array

    string[] listOne = new string[] { "dog", "cat", "car", "apple"};
    string[] listTwo = new string[] { "car", "apple"};

    What I need is to order listOne by the order of items in listTwo (if present). So the new list would be in this order; "car", "apple", "dog", "cat"

  2. #2
    Join Date
    Feb 2011
    United States

    Re: linq on two string array

    I don't know of a quick way to do it with Linq (probably because I don't use Linq terribly often, perhaps another member will know).

    You can do it normally though, if you have a way to quickly test membership in both lists.

    List<string> orderedResult = new List<string>();
    for(int i = 0; i < listTwo.Length; i++)
        if( isMember(listTwo[i], listOne) )  //If the i'th item in list2 is contained in list1
    for(int i = 0; i < listOne.Length; i++)
        if( !isMember(listOne[i], listTwo) ) //If the i'th item in list1 is NOT contained in list2
    For short lists, it is probably sufficient to implement isMember as a loop. If you had longer lists, you'd probably want to construct a dictionary for each list:
    Dictionary<string, int> listOneDict = new Dictionary<string, int>();
    foreach(string s in listOne)
        listOneDict.Add(s, 0);
    And then test for membership:
    All of these snippets assume that listOne and listTwo have no repeated elements.

    Anyway, I think that ought to work, but I didn't explicitly test it. Push back if you need more information. Hope that is a little helpful!
    Best Regards,

    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)

We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.