如何将List <string>添加到需要SampleSentence而不是List <string>的对象?

时间:2016-06-01 11:39:33

标签: c#

我用这个课来描述一个例句。

public class SampleSentence
{
    public int SampleSentenceId { get; set; } // SampleSentenceId (Primary key)
    public int WordFormId { get; set; } // WordFormId
    public string Text { get; set; } // Text
    public int SourceId { get; set; } // SourceId
    public int StatusId { get; set; } // StatusId

    // Foreign keys
    public virtual WordForm WordForm { get; set; } // FK_SampleSentenceWordForm

    public SampleSentence()
    {
        SourceId = 1;
        StatusId = 1;
    }
}

和SampleSentences是WordForms的一部分:

public class WordForm
{
    public int WordFormId { get; set; } // WordFormId (Primary key)
    public int WordId { get; set; } // WordId
    public string Definition { get; set; } // Definition (length: 200)
    public int PosId { get; set; } // PosId
    public int SourceId { get; set; } // SourceId
    public int StatusId { get; set; } // StatusId

    // Reverse navigation
    public virtual System.Collections.Generic.ICollection<SampleSentence> SampleSentences { get; set; } // SampleSentence.FK_SampleSentenceWordForm
    public virtual System.Collections.Generic.ICollection<Synonym> Synonyms { get; set; } // Synonym.FK_SynonymWordForm

    // Foreign keys
    public virtual Pos Pos { get; set; } // FK_WordFormPos
    public virtual Word Word { get; set; } // FK_WordFormWord

    public WordForm()
    {
        SourceId = 1;
        StatusId = 1;
        SampleSentences = new System.Collections.Generic.List<SampleSentence>();
        Synonyms = new System.Collections.Generic.List<Synonym>();
    }
}

我知道如何创建一个像这样的新WordFrom:

var wordForm = new WordForm()
                        {
                            WordId = word.WordId,
                            Definition = result.definition,
                            SampleSentences = sampleSentences
                            PosId = pos
                        };

但鉴于我的SampleSentences是这样的:

List<string> = sampleSentences

如何将sampleSentences添加到wordForm?

2 个答案:

答案 0 :(得分:2)

我会尽量让它尽可能简单:

//As sampleSentences are List of strings 
var newListOfSentences = new List<SampleSentence>();

foreach (string value in sampleSentences)
    {
        var newSentence = new SampleSentence();
        newSentence.Text  = value ;
        //and the others...
        newListOfSentences.Add(newSentence);
    }

最后你有:

    SampleSentences = newListOfSentences

答案 1 :(得分:1)

假设您的列表sampleSentences仅包含SampleSentence个实例的ID,您可以使用以下内容轻松将实际实例添加到WordForm

var allSentences = // .. get all SampleSentences from your DB or whatever
myWordForm.SampleSentences = allSentences
    .Where(x => sampleSentences.Select(y => Convert.ToInt32(y)).Contains(x.SampleSentenceId));

无论如何,您应该将实例的ID存储在List<int>而不是List<string>,因为SampleSentenceId已经 是整数。

否则,如果您的samleSentences - 列表引用Text - SampleSentence - 属性,则可以写下此内容:

myWordForm.SampleSentences = allSentences.Where(x => sampleSentences.Contains(x.Text));