views:

95

answers:

1

I have a List of concrete objects. Some require to be analyzed to take a decision to which one will be kept (when the group contain more than 1 occurence).

Here is a simplified example:

 List<MyObject> arrayObject = new List<MyObject>();
 arrayObject.Add(new MyObject { Id = 1, Name = "Test1", Category = "Cat1"});
 arrayObject.Add(new MyObject { Id = 2, Name = "Test2", Category = "Cat2" });
 arrayObject.Add(new MyObject { Id = 2, Name = "Test2", Category = "Cat3" });

This will required to be at the end of the analyze only :

 arrayObject.Add(new MyObject { Id = 1, Name = "Test1", Category = "Cat1"});
 arrayObject.Add(new MyObject { Id = 2, Name = "Test2", Category = "Cat3" });

As you see the Id2 with Cat2 is gone because the business logic took it off. So what should be done is to be able to get those who have more than 1 category and to apply a logic on it.

Here is what I have so far :

        List<MyObject> arrayObject = new List<MyObject>();
        arrayObject.Add(new MyObject { Id = 1, Name = "Test1", Category = "Cat1"});
        arrayObject.Add(new MyObject { Id = 2, Name = "Test2", Category = "Cat2" });
        arrayObject.Add(new MyObject { Id = 2, Name = "Test2", Category = "Cat3" });


        var filtered = from arrayObject1 in arrayObject
                        group arrayObject by new { arrayObject1.Id, arrayObject1.Name }
                        into g
                        select new { KKey = g.Key, Obj = g };


        foreach(var c in filtered)
        {
            Console.WriteLine(c.KKey + ":" + c.Obj.Count());
            foreach (var cc in c.Obj)
            {
                //Put some Business Logic here to get only 1... but to simplify will just print
                Console.WriteLine("--->" + cc);
            }
        }

The problem is 1) cc is not of type MyObject, second, I have to get all properties in the group by new... I might have few objects that will be different.

Is it possible with Linq? Cause, I can do it without using Linq... but I am trying to apply new stuff of this framework (3.5) as much as I can. Thank

+3  A: 

The problem is in the line that says:

group arrayObject by

It should say:

group arrayObject1 by
Vojislav Stojkovic
Oh my! Not it works. Do you have an idea that will let me not have to add all field in the group arrayObject1 by new { arrayObject1.Id, arrayObject1.Name }. In fact the real object has several property. Isn't there a way to group by "all field except x"?
Daok