2

これがLinqpadで機能する例です。問題は、2つ以上の単語で機能する必要があることです。たとえば、searchString = "headboardbedrailing"です。これはインデックスに対するクエリであり、私が行った「Match Any Word」の代わりに、「Match All Words」に必要です。ここで、検索された各単語に共通のキー値が検索されます。

//Match ALL words for categories in index
string searchString = "headboard bed";

List<string> searchList = new List<string>(searchString.Split(' '));

string word1 = searchList[0];
string word2 = searchList[1];

var List1 = (from i in index
            where i.word.ToUpper().Contains(word1)
            select i.category.ID).ToList();         

var List2 = (from i in index
            where i.word.ToUpper().Contains(word2)
            select i.category.ID).ToList();             

//How can I make this work for more than two Lists?
var commonCats = List1.Intersect(List2).ToList();

var category = (from i in index
           from s in commonCats
           where commonCats.Contains(i.category.ID)
           select new 
           {
               MajorCategory = i.category.category1.description,
               MinorCategory = i.category.description,
               Taxable = i.category.taxable,
               Life = i.category.life,
               ID = i.category.ID
           }).Distinct().OrderBy(i => i.MinorCategory);

category.Dump();

ありがとう!

4

2 に答える 2

3

交差点の交差点は可換で連想的です。これは、(A∩B∩C)=(A∩(B∩C))=((A∩B)∩C)を意味し、リストの順序を並べ替えても結果は変わりません。したがって、.Intersect()複数回適用するだけです。

var commonCats = List1.Intersect(List2).Intersect(List3).ToList();

したがって、コードをより一般的にするには、次のようにします。

var searchList = searchString.Split(' ');

// Change "int" if this is not the type of i.category.ID in the query below.
IEnumerable<int> result = null;

foreach (string word in searchList)
{
    var query = from i in index
                where i.word.ToUpper().Contains(word1)
                select i.category.ID;

    result = (result == null) ? query : result.Intersect(query);
}

if (result == null)
    throw new InvalidOperationException("No words supplied.");

var commonCats = result.ToList();
于 2011-09-06T17:05:52.123 に答える
0

@cdhowieの答えに基づいて構築するには、なぜ使用するのIntersectですか?複数のステップでクエリを作成することで、より効率的にできると思います。何かのようなもの...

if(string.IsNullOrWhitespace(search))
{
    throw new InvalidOperationException("No word supplied.");
}

var query = index.AsQueryable();

var searchList = searchString.Split(' ');

foreach (string word in searchList)
{
    query = query.Where(i => i.word.ToUpper().Contains(word));
}

var commonCats = query.Select(i => i.category.ID).ToList();
于 2011-09-06T17:33:51.370 に答える