1

I have a immutable List.

In the below g.Select(...) I do a .ToList() which is put into the MemberIdList. I do not want to create a new List with ToList() rather I want to add each r.Field string to the immutable List inside the unit object.

How can I do this?

var groupedCollection = table.AsEnumerable()
        .GroupBy(row => new
        {
            UType = row.Field<string>("UnitType"),
            UZoom = row.Field<string>("UnitZoom"),
            MZoom = row.Field<string>("MemberZoom"),
        });

    var unitCollection = groupedCollection
        .Select(g => new Unit
        {
            UnitType = g.Key.UType,
            UnitZoom = g.Key.UZoom,
            MemberZoom = g.Key.MZoom,
            MemberIdList = g.Select(r => r.Field<string>("TestId")).ToList(),
        });

    List<Unit> units = unitCollection.ToList();


public class Unit
{
    public Unit()
    {
        MemberIdList = new List<String>();
    }

    public String UnitType { get; set; }
    public String UnitZoom { get; set; }
    public String MemberZoom { get; set; }
    public int MemberOrder { get; set; }

    public List<String> MemberIdList { get; private set; }
}
7
  • In my context MemberIdList.AddRange(g.Select(r => r.Field<string>("TestId"))); does not work. Typing MemberIdList. there is no AddRange. Commented Jun 9, 2011 at 18:32
  • @msfanboy are you sure it is a List<T> then? As that definitely has AddRange. You will of course need to tell it the instance, I.e. Obj.MemberIdList.AddRange() Commented Jun 9, 2011 at 18:40
  • 1
    Btw ; List<T> is never immutable. A list-property without a setter is very different to an immutable list. Commented Jun 9, 2011 at 18:46
  • but I have a private setter?? Commented Jun 9, 2011 at 21:00
  • @msfanboy so? that just means you can't change it to a different list. I can still call yourList.Add(x) - the list is not internally immutable. Commented Jun 9, 2011 at 21:01

1 Answer 1

2

Why not just create a constructor for Unit that takes the data for MemberIdList like:

public Unit(IEnumerable<string> memberIdList)
{
    MemberIdList = new List<string>(memberIdList);
}

and modify your select to:

.Select(g => new Unit(g.Select(r => r.Field<string>("TestId")))
{
    UnitType = g.Key.UType,
    UnitZoom = g.Key.UZoom,
    MemberZoom = g.Key.MZoom
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.