0

ASP.NETMVCプロジェクトでEntityFrameworkを使用しています。

以下のエンティティがあるとしましょう:

public class Project
{
    public int ProjectID { get; set; }
    public string Description { get; set; }
    public string Tags { get; set; }
}

DBに次のデータがあるとします。

ProjectID: 1
Description: "My first element"
Tags: "one, three, five, seven"

ProjectID: 2
Description: "My second element"
Tags: "one, two, three, six"

ProjectID: 3
Description: "My third element"
Tags: "two, three, four"

すべてのレコードからすべてのタグを収集したいと思います。つまり、「1、2、3、4、5、6、7」

どのようにできるのか?これはばかげた質問に思えるかもしれませんが、どうすればよいかわかりません。

ありがとう。

4

3 に答える 3

0

string.Split()リスト内の各タグを掘り下げるためにを使用する必要があります。

HashSet<string> allTags = new HashSet<string>();
foreach(Project project in context.Projects)
{
    string tagsList = project.Tags;
    string[] separateTags = tagsList.Split(", ", StringSplitOptions.RemoveEmptyEntries);
    foreach(string separateTag in separateTags)
    {
        allTags.Add(separateTag);
    }
}

その後allTags、すべてのタグが含まれます。それらをもう一度1つの大きな文字列に入れたい場合は、を使用しますstring.Join

于 2012-09-01T14:38:17.760 に答える
0

文字列を分割した後、SelectMany()を使用してコレクションを連結し、を使用Distinct()して重複を削除できます。

var tags = context.Projects
               .SelectMany(p => p.Tags.Split(", ", StringSplitOptions.RemoveEmptyEntries))
               .Distinct();

クエリ構文バージョンは次のとおりです。これはSelectMany()、舞台裏でステートメントに変換されます。

var tags = (from p in project
            from tag in p.Tags.Split(", ", StringSplitOptions.RemoveEmptyEntries)
            select tag).Distinct();
于 2012-09-01T18:05:47.993 に答える
0

残念ながら、Split()はSQLに変換されないため、メモリ内で変換する必要があります。次のことをお勧めします。

var tags = context.Projects
    // pull only the tags string into memory
    .Select(p => p.Tags) 
    // operate in memory from this point on
    .AsEnumerable()
    // remove empty entries so you don't get "" interpreted as one empty tag
    .SelectMany(tags => tags.Split(",", StringSplitOptions.RemoveEmptyEntries))
    // assuming you don't want leading or trailing whitespace
    .Select(tag => tag.Trim())
    .ToList();
于 2012-09-01T18:16:03.160 に答える