为什么我只在这个foreach语句中收到一个Object?

时间:2013-12-17 11:00:17

标签: c# visual-studio-2010 foreach

我对这段代码感到很生气:

Entity.GuidArrayArray.gaa[0]) is a static Guid[][]
Entity.Customer is an non static ClassObject with several propperties e.G .id which is a Guid
Entity.DataSource.LbCustomer.CustomerSource is a static BindingList<Entity.Customer>
Entity.CustomerCollection.customerCollection is a static List<Entity.Customer>

gaa [0]包含6个不同的Guids,它们等于customerCollection中相同Am顾客的.id。在此代码启动之前,CustomerSource包含customerCollection的克隆。

我希望获得的结果(在这种特殊情况下)(与之前相同)将customerCollection中的每个对象的克隆添加到CustomerSource中。我得到的只是列表中的最后一个对象。我猜它与foreach语句有关,gaa [0]中的每个guid选择其连接的Object并覆盖previos,但我认为没有办法阻止它。我希望你有任何想法吗?

    public static void GuidInput()
    {
        CustomerFiller(Entity.GuidArrayArray.gaa[0]);
    }

    private static void CustomerFiller(Guid[] guidArray)
    {
        foreach (Guid g in guidArray)
            Entity.DataSource.LbCustomer.CustomerSource = ToBindingList(Entity.CustomerCollection.customerCollection.Where(a => a.id == g).ToList());
    }

    private static BindingList<T> ToBindingList<T>(List<T> input)
    {

        BindingList<T> output = new BindingList<T>(Clone(input));
        return output;
    }
    private static List<T> Clone<T>(IEnumerable<T> input)
    {
        List<T> clonedList = new List<T>(input);
        return clonedList;
    }

编辑:


解决方案:

private static void CustomerFiller(Guid[] guidArray)
    {
        foreach (Guid g in guidArray)
        {
            List<Entity.Customer> abc =new List<Entity.Customer>();
            foreach (Guid g in guidArray)
                abc.AddRange(Entity.CustomerCollection.customerCollection.Where(a => a.id == g));
            Entity.DataSource.LbCustomer.CustomerSource = ToBindingList(abc);
            Entity.DataSource.LbCustomer.CustomerSource = Reduce(Entity.DataSource.LbCustomer.CustomerSource, x => x.id);
        }

但我仍然希望摆脱这种前瞻。

1 个答案:

答案 0 :(得分:2)

试试这个:

private static void CustomerFiller(Guid[] guidArray)
{       
  Entity.DataSource.LbCustomer.CustomerSource = ToBindingList(Entity.CustomerCollection.customerCollection.Where(a => guidArray.Contains(a.id) ).ToList());
}