1

我有以下代码用于使用 Entity Framework 将数据放入关系表中:

    public IList<Objective> createObjectives()
    {
        var objectiveNames = new[]
        {
            "Objective 1",
            "Objective 2",
            "Objective 3",
            "Objective 4",
            "Objective 5",
            "Objective 6",
            "Objective 7",
            "Objective 8"
        };
        var objectives = objectiveNames.Select(o => new Objective
        {
            ObjectiveSeq = ??,
            Name = o,
            Description = o + " Description",
            ModifiedDate = DateTime.Now
        }
        );
        return objectives.ToList();
    }

我的表名 ObjectiveSeq 中有一个新字段。如何修改我的 LINQ 以在该字段中插入从 1 开始的序列号。

4

2 回答 2

1
 var objectives = objectiveNames.Select((o, index) => new Objective
        {
            ObjectiveSeq = index,
            Name = o,
            Description = o + " Description",
            ModifiedDate = DateTime.Now
        }
        );
于 2013-03-27T02:43:54.883 回答
0

函数有过载Select。你可以在这里找到它。

Enumerable.Select<TSource, TResult> Method (IEnumerable<TSource>, Func<TSource, Int32, TResult>)

查看页面中显示的示例。

 string[] fruits = { "apple", "banana", "mango", "orange", "passionfruit", "grape" };

 var query = fruits.Select((fruit, index) => new { index, str = fruit });

 foreach (var obj in query)
 {
    Console.WriteLine("{0}", obj);
 }

你可以看到我们正在使用(fruit, index). 您正在选择元素和索引。

输出将是

{ index = 0, str = apple }
{ index = 1, str = banana }
{ index = 2, str = mango }
{ index = 3, str = orange }
{ index = 4, str = passionfruit }
{ index = 5, str = grape }
于 2013-03-27T02:42:35.230 回答