如何使用LINQ将序列号插入字段?

时间:2013-03-27 02:39:59

标签: c# linq

我使用以下代码将数据放入使用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开始在该字段中插入序号。

2 个答案:

答案 0 :(得分:1)

 var objectives = objectiveNames.Select((o, index) => new Objective
        {
            ObjectiveSeq = index,
            Name = o,
            Description = o + " Description",
            ModifiedDate = DateTime.Now
        }
        );

答案 1 :(得分:0)

Select功能出现过载。你可以找到它here

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 }