views:

115

answers:

3

I can do this by looping the result of a simplified query:

var query = from myrecord in dt.AsEnumerable()
    where myrecord.Field<string>("field1") == "value1" || myrecord.Field<string>("field1") == "value2"
    select myrecord;

foreach(var myrecord in query)
{
    //if value1, then "X"
    //sum += field2
}

But, I want to know if it's possible within the LINQ statement.

Anonymous class with two members: Name and Value. Name is "X" or "Y" depending on field1 and Value is the sum of all field2 values for records where the conditions are met. I think I need to use the Count() method, but I'm not sure how or where. Maybe I need to use "group" and "into" to get the count from a temporary table?

If there are records with (field1 == "value1"), the string will be "X" else the string will be "Y".

var query = from table in dt.AsEnumerable()
    where table.Field<string>("field1") == "value1" || 
        table.Field<string>("field1") == "value2"
    select new
    {
        Name = (condition ? "X" : "Y"),
        Value = //sum all field2 values
    };

Thanks in advance!

A: 

sure you can, Following sample works similarly

class Program
    {
        static void Main(string[] args)
        {
            List<Person> persons= new List<Person>();
            var result = from p in persons
            select new
             {
              Name = (s.IsMarried ? s.X : s.Y)
             };
        }
    }
    class Person
    {
        public bool IsMarried { get; set; }
        public string X { get; set; }
        public string Y { get; set; }
    }
Asad Butt
i think i phrased my question wrong, but this does answer the question asked. i think i am trying to use the LINQ query to build one record/one instance of the anonymous class and not a set.
David
A: 

You just use the "table" variable that you already have.

var query = from table in dt.AsEnumerable() 
where table.Field<string>("field1") == "value1" ||  
    table.Field<string>("field1") == "value2" 
select new 
{ 
    Name = (table.whatever ? "X" : "Y"), 
    Value = table.something.Sum()
}; 
John Fisher
A: 

You can just get the sum of the table by doing

table.Sum(t => t.ValueToSum) //Or whatever sub-table you need to sum
NPayette