none
LINQ query for expected data set. RRS feed

  • Question

  • Hello

    I have folloing data set :

    ID   Ticker

    1     A

    2     B

    3     C

    4     B

    5     A

    6     D

    Now i want to get following result through LINQ query:

    ID   Ticker

    1     A

    5     A

    2     B

    4     B

    In the result set there are only data which has multiple Ticker with corresponding ID.

    It will be helpful for me if you provide me the LINQ query for expected data set .

    Thanks

    Wednesday, December 8, 2010 10:27 AM

Answers

  • Perhaps a Group statement?
    This is LINQ to Object but should work the same for your typed dataset.

        class TickClass
        {
          public int ID { get; set; }
          public string Ticker { get; set; }
        }
    
        static void Main(string[] args)
        {
    
          List<TickClass> tickerList = new List<TickClass>()
          {
            new TickClass{ID = 1, Ticker = "A"},
            new TickClass{ID = 2, Ticker = "B"},
            new TickClass{ID = 3, Ticker = "C"},
            new TickClass{ID = 4, Ticker = "B"},
            new TickClass{ID = 5, Ticker = "A"},
            new TickClass{ID = 6, Ticker = "D"},
          };
    
    
          var q = from t in tickerList
              group t by t.Ticker
                into tg
                where tg.Count() >= 2
                select tg;
    
          foreach (var tickerGroup in q)
          {
            foreach (var ticker in tickerGroup)
            {
              Console.WriteLine("{0} {1}", ticker.ID, ticker.Ticker);
            }
          }
        }
    


    Output:

    1 A
    5 A
    2 B
    4 B


    This posting is provided "AS IS" with no warranties.
    • Marked as answer by liurong luo Tuesday, December 14, 2010 6:31 AM
    Wednesday, December 8, 2010 1:06 PM