如何使用序列号创建一个集合作为C#中另一个集合中的一个字段

时间:2013-12-28 17:36:54

标签: c#

我有一个包含AnswerDetail对象集合的变量Answers:

IEnumerable<AnswerDetail> Answers = ...

AnswerDetail类:

public class AnswerDetail
{
    public int AnswerId { get; set; }
    public string Text { get; set; }
    public bool? Correct { get; set; }
    public bool? Response { get; set; }
}

AnswerId对于应用程序来说是独一无二的,但我想改变这一点 它们是从1开始的连续数字。如何填充以下内容 class,在源对象Answers中交换长数并放入 数字1,2,3等到AnswerUid字段而不是原始数字。换句话说,我想在将它发送到客户端时完全丢失AnswerId号码,而只是发送简单的序列号。

public class AnswerDetailToClient
{
    public int AnswerUId { get; set; }
    public string Text { get; set; }
    public bool? Correct { get; set; }
    public bool? Response { get; set; }
}

2 个答案:

答案 0 :(得分:5)

您可以使用Select方法重载,该方法需要Func<TSource, int, TResult>委托:

return Answers.Select((x,i) => { x.AnswerUID = i; return x; });

使用i更改i + 1以从1开始,否则它将从0开始。

但它也会修改你的Answers集合项,因为它们是引用类型实例。您可以在更改ID之前克隆对象以防止:

return Answers.Select(x => x.Clone())
              .Select((x,i) => { x.AnswerUID = i; return x; });

您必须实施Clone方法才能使其正常运行。

答案 1 :(得分:0)

这是我简单的解决方案。

var list = new List<AnswerDetailToClient>();
list.Add(new AnswerDetailToClient{AnswerUId = 100, Correct = true, Response = false, Text = "Bla bla"});
list.Add(new AnswerDetailToClient { AnswerUId = 111, Correct = true, Response = false, Text = "Bla bla" });
list.Add(new AnswerDetailToClient { AnswerUId = 222, Correct = true, Response = false, Text = "Bla bla" });
list.Add(new AnswerDetailToClient { AnswerUId = 333, Correct = true, Response = false, Text = "Bla bla" });
list.Add(new AnswerDetailToClient { AnswerUId = 444, Correct = true, Response = false, Text = "Bla bla" });
list.Add(new AnswerDetailToClient { AnswerUId = 555, Correct = true, Response = false, Text = "Bla bla" });

int i = 0;
var q = (from t in list
    let x = ++i
    select new
    {
        asnswerId= x,
        correct = t.Correct,
        response = t.Response,
        text = t.Text
    });
foreach (var l in q)
{
    Console.WriteLine(l.asnswerId);
}
Console.Read();