tags:

views:

77

answers:

2

I'm building a word anagram program that uses a database which contains one simple table:

Words
---------------------
varchar(15) alphagram
varchar(15) anagram
(other fields omitted for brevity)

An alphagram is the letters of a word arranged in alphabetical order. For example, the alphagram for OVERFLOW would be EFLOORVW. Every Alphagram in my database has one or more Anagrams. Here's a sample data dump of my table:

Alphagram   Anagram  
EINORST     NORITES
EINORST     OESTRIN
EINORST     ORIENTS
EINORST     STONIER
ADEINRT     ANTIRED
ADEINRT     DETRAIN
ADEINRT     TRAINED

I'm trying to build a LINQ query that would return a list of Alphagrams along with their associated Anagrams. Is this possible?


UPDATE: Here's my solution based on the suggestions below! Thanks all!

using (LexiconEntities ctx = new LexiconEntities())
{
    var words = ctx.words;

    var query =
        from word in words
        where word.alphagram == "AEINRST"
        group word by word.alphagram into alphagramGroup
        select new { Alphagram = alphagramGroup.Key, Anagrams = alphagramGroup };

    foreach (var alphagramGroup in query)
    {
        Console.WriteLine("Alphagram: {0}", alphagramGroup.Alphagram);
        foreach (var anagram in alphagramGroup.Anagrams)
        {
            Console.WriteLine("Anagram: {0}", anagram.word1);
        }
    }
}
+2  A: 
moi_meme
The GroupBy was the key! Cheers!
eponymous23
A: 
    var words = new List<Words>() 
    { 
        new Words("EINORST", "NORITES"), 
        new Words("EINORST", "OESTRIN"), 
        new Words("EINORST", "STONIER"), 
        new Words("ADEINRT", "ANTIRED"), 
        new Words("ADEINRT", "DETRAIN"), 
        new Words("ADEINRT", "TRAINED")
    };       


    var result = words.GroupBy(w => w.Alphagram, w => w.Anagram)
                      .Select(w => new { 
                                            Alphagram = w.Key, 
                                            Anagrams = w.Where(p => w.Key.ToCharArray().SequenceEqualUnOrdered(p.ToCharArray())).ToList() 
                                       } 
                             )
                      .ToList();


public static bool SequenceEqualUnOrdered<T>(this IEnumerable<T> first, IEnumerable<T> second)
{
    return new HashSet<T>(first).SetEquals(second);
}

Is it what you are looking for? It is LINQ to Objects. You may want to use LINQ-to-SQL or LINQ-to-Entites to fetch your records into your objects and then use the above-mentioned LINQ-to-Objects query over the already-fetched object collection.

Kthurein