按键使用list <int>作为linq组

时间:2015-07-31 02:03:42

标签: c# linq grouping

这是来自LinqPad(因此是.Dump())

void Main()
{
    var k1 = new List<int>(){1,2,3,4,5};
    var k2 = new List<int>(){1,2,3,4,5};

    var o1 = new A(){k=k1, objectName="o1"};
    var o2 = new A(){k=k2, objectName="o2"};

    var l = new List<A>();

    l.Add(o1);
    l.Add(o2);

    var b = from a in l 
    group a.objectName by a.k into g
    select new {g.Key, n = String.Join(",",g)};

    b.Dump();
}

public class A {
    public List<int> k;
    public string objectName;
}

问题在于它不起作用,上面的代码产生了:

enter image description here

我知道为什么会发生这种情况,因为列表对象是单独的对象,但我想知道的是,是否有办法告诉group by使用列表的内容而不是对象实例。

3 个答案:

答案 0 :(得分:2)

public static void Main()
{
    var k1 = new List<int>(){1,2,3,4,5};
    var k2 = new List<int>(){1,2,3,4,5};

    var o1 = new A(){k=k1, objectName="o1"};
    var o2 = new A(){k=k2, objectName="o2"};

    var l = new List<A>();

    l.Add(o1);
    l.Add(o2);

    // Use custom comparer for the list
    var b = l.GroupBy(a => a.k, new ListComparer<int>())
             .Select(g => new 
                {
                    Key = String.Join(",", g.Key.Select(i => i)), 
                    n = String.Join(",",g.Select(i => i.objectName))
                });


    foreach(var item in b)
    {
        Console.WriteLine(string.Format("{0} : {1}", item.Key, item.n));
        // 1,2,3,4,5 : o1,o2
    }
}

public class A
{
    public List<int> k;
    public string objectName;
}


public class ListComparer<T> : IEqualityComparer<List<T>>
{
    // Ignore the order and compare with the sequence value for the equality
    public bool Equals(List<T> left, List<T> right)
    {
        return left.OrderBy(i => i).SequenceEqual(right.OrderBy(i => i));
    }

    public int GetHashCode(List<T> list)
    {
        return list.Count;
    }
}

.Net Fiddle

答案 1 :(得分:2)

您可以将数组转换为字符串。

void Main()
{
    var builder = new ContainerBuilder();
    builder.RegisterType<EventStore>().AsSelf();
    builder.Register(cc => new DebugingEventStore(cc.Resolve<EventStore>())).As<IEventStore>();
    var container = builder.Build();

    container.Resolve<IEventStore>().DoWork();

}

public interface IEventStore
{
    void DoWork();
}

public class EventStore : IEventStore
{
    public EventStore(Foo doo, Bar bar)
   { ....} 
    void IEventStore.DoWork()
    {
        Console.WriteLine("EventStore");
    }
}

public class DebuggingEventStore: IEventStore
{
    private IEventStore _internalEventStore;

    public DebuggingEventStore(IEventStore eventStore)
    {
        this._internalEventStore = eventStore;
    }
    void IEventStore.DoWork()
    {
        this._internalEventStore.DoWork();
        Console.WriteLine("DebuggingEventStore");
    }
}

答案 2 :(得分:0)

我成功完成了以下任务:

var b = l.SelectMany(a => a.k.Select(i =>  new { Key = i, n = a.objectName }))
         .GroupBy(i => i.Key);

UITableViewCell Class Reference