Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I have this code
var result = from row in DTgraph.AsEnumerable()
group row by row.Field<string>("Campaign") into grp
select new
{
Campaign = grp.Key,
Count = grp.Count(),
SL = grp.Sum(s => s.Field<Decimal>("Inb.ServiceLevel"))
};
Where the DTgraph is a DataTable
I want to make loop on result. How please?
You can use foreach:
foreach (var item in result)
{
//Your code here
}
Or for to know the index. But you have to add .ToList() at the end of your LINQ:
var result = (from row in DTgraph.AsEnumerable()
group row by row.Field<string>("Campaign") into grp
select new
{
Campaign = grp.Key,
Count = grp.Count(),
SL = grp.Sum(s => s.Field<Decimal>("Inb.ServiceLevel"))
}).ToList();
for (int i = 0; i < result.Count(); i++)
{
//Your code here
//Now you can do result[i].Something
}
Here is a loop:
foreach (var item in result)
{
//your logic to each item of loop
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am trying to get the count for the most common duplicate item in a list.
So far, I have:
List<string> brandList = new List<string>();
which contains 5 different soft drink brands, and the count is 100. I need to find out which brand has the most duplicates in the list and count how many duplicates there are.
Presuming that your pseudo code actually was:
List<Brand> brandList=new List<Brand>();
// fill list
and your Brand class either overrides Equals+getHashCode or has a property like BrandID which is the identifier. N youow want to get the count of the most popular brand, you can use LINQ:
var mostPopularBrand = brandList.GroupBy(b => g.BrandID)
.OrderByDescending(g => g.Count())
.Select(g => new { BrandID = g.Key, Count = g.Count()})
.First();
Console.WriteLine("Most poular brand: {0} Count: {1}",
mostPopularBrand.BrandID, mostPopularBrand.Count);
Update: If it's actually a List<string>(question was edited):
var mostPopularBrand = brandList.GroupBy(str => str)
.OrderByDescending(g => g.Count())
.Select(g => new { Brand = g.Key, Count = g.Count()})
.First();
Your code doesn't compile. Providing that you mean List<String> as a storage of brands:
var ListbrandList = new List<String>() {
"Cola",
"Juice",
"Cola",
"Water",
"Milk",
"Water",
"Cola",
};
var result = ListbrandList
.GroupBy(item => item)
.Select(item => new {
Name = item.Key,
Count = item.Count()
})
.OrderByDescending(item => item.Count)
.ThenBy(item => item.Name);
String report = String.Join(Environment.NewLine, result
.Select(item => String.Format("{0} appears {1} time(s)", item.Name, item.Count)));
you'll have report as
Cola appears 3 time(s)
Water appears 2 time(s)
Juice appears 1 time(s)
Milk appears 1 time(s)
var result = brandList
.Distinct()
.GroupJoin(brand,
k => k,
b => b,
(k, b) => new { BrandName = k, Count = b.Count() });
// An usage could be...
foreach (var r in result)
{
Debug.WriteLine("{0} Brand has {1}", r.BrandName, r.Count);
}
Without LinQ:
var result = new Dictionary<string, int>();
foreach (var brand in brandList)
{
if (!result.ContainsKey(brand))
{
var count = brandList.FindAll(x => x.Equals(brand)).Count;
result.Add(brand, count);
}
}
foreach (var r in result)
{
Console.WriteLine("{0} Brand has {1}", r.Key, r.Value);
}
You can try to do group using LINQ by Elements and calculate count
var groupedList = from l in ListbrandList
group l by l into grp
select new { key = grp.Key, cnt = grp.Count()};
Then you will have group by key (Element) and value (Count)
Something like this maybe:
var res = brandList.GroupyBy(x => x)
.Select(x => new {Key = x.Key, Count = x.Count});
Now you have a list containing the actual drink-number and the count for this number.
EDIT: Getting the brand with most count is now easy, e.g. by using:
var mostPopular = res.Single(x => x.Count == res.Max(y => y.Count));
EDIT2: Without LINQ the following might work, which is way longer and more complicated:
// get the count for every brand
Dictionary<string, int> res = new Dictionary<string, int>();
foreach(var x in brands)
{
if (!res.ContainsKey(x)) res[x] = 0;
res[x]++;
}
// now get the max count
int currentMax = 0;
string key = "";
foreach (var kv in res)
{
if (kv.Value > currentMax)
{
currentMax = kv.Value;
key = kv.Key;
}
}
Now the key should contain the brand with highest Count.
To count element with specific value in a list use :
int quantity = lst.Count(r => r == "Cola");
Example :
List<string> lst = new List<string>()
{
"Sprite",
"Cola",
"Sprite",
"Sprite",
"Cola",
"Sprite",
"Sprite",
"Cola",
"Pepsi",
"Sprite",
"Pepsi",
"Sprite",
};
string[] popularBrands = { "Cola", "Pepsi" };
int[] quantities = new int[popularBrands.Length];
for (int i = 0; i < popularBrands.Length; i++)
{
quantities[i] = lst.Count(r => r.ToUpper() == popularBrands[i].ToUpper());
Console.WriteLine("{0} : {1}", popularBrands[i], quantities[i]);
}
Output
Cola : 3
Pepsi : 2
P.S.
About this code r => r.ToUpper() == popularBrands[i].ToUpper() :
r is variable that holds a value from our list (that are taken one by one). We also use ToUpper() to make sure that our check is case insensitive.
So we basically loop through the collection taking values out of it one by one. Each time we put value to r variable and check if this variable satisfies condition. If so - we count it, if not - we just move to next value.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
how to convert to lambda:
var source = new Item[]{
new Item { Key = "A", ID = 1, Text = "Hello" },
new Item { Key = "A", ID = 2, Text = "World" },
new Item { Key = "B", ID = 2, Text = "Bar" },
new Item { Key = "B", ID = 1, Text = "Foo" }
};
var results = (from r in source
group r by r.Key.ToString() into g
select new
{
g.Key,
Data = string.Join("", g.OrderBy(s => s.ID).Select(s => s.Text))
});
It is possible to convert?
Thanks for answer
How about this?
var results = source.GroupBy(r => r.Key).Select(g => new
{
g.Key,
Data = string.Join("", g.OrderBy(s => s.ID).Select(s => s.Text))
});
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a list something like that
var x = new List<string>{"A","B","C","D","E","F"};
I want to group it in doubles like that
1-A
1-B
2-C
2-D
3-E
3-F
What my solution is
var result = new Dictionary<int, List<string>>();
var sequence = 1;
var groupList = new List<string>();
for (var i = 0; i < x.Length ; i++)
{
groupList.Add(x[i]);
if ((i + 1)%2 == 0)
{
result.Add(sequence, groupList);
groupList = new List<string>();
sequence++;
}
}
return result;
I am looking for alternative (better) ways to get same result.
Here is another way:
int numPairs = 3;
char[] abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
var dict = new Dictionary<int, char[]>();
for (int i = 1, k=1; i <= numPairs && k<abc.Length; i++, k+=2)
{
dict.Add(i, new char[] { abc[k - 1], abc[k] });
}
return dict;
This will do the same.
var y = x.GroupBy(i =>Convert.ToInt32((x.IndexOf(i) + 1.1) * 0.5));
I think this is a readable Linq solution:
var result = x
.Select((value, index) => new { value, index })
.GroupBy(arg => arg.index / 2 + 1, arg => arg.value);
The Select projects the value with its index into an anonymous type, and the GroupBy groups by the index.
If you need the groupings in a Dictionary like in your question, use ToDictionary:
var dictionary = result.ToDictionary(
grouping => grouping.Key,
grouping => grouping.ToList());
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Model.GetData.Where(p => p.Value != null).ToList();
I have values in my database like below,
My Value Column:
Null
Null
5
16
ExampleValue1
ExampleValue2
p.value is string
I only want to see "ExampleValue1" and "ExampleValue2".
How can i get datas not null and not numeric ?
Perhaps:
var BillingNumbers = Model.GetData
.Where(p => p.Value != null && SqlFunctions.IsNumeric(p.Value) == 0);
Assuming the results are of different types, you can query by type like this:
var results = from item in collection where (item is String) select item;
Example program:
static void Main(string[] args)
{
var collection = new List<Object>
{
5,
1.5,
null,
"foo",
"bar",
};
var results = from item in collection where (item is String) select item;
foreach (var result in results)
{
Console.WriteLine(result);
}
System.Threading.Thread.Sleep(10000);
}
You can rely to this code :
result is just contains string
List<object> result = new List<object>();
var MyList = new List<Object>{
523,
2.555,
null,
"ExampleValue1",
"ExampleValue2",
};
MyList.ForEach(x =>
{
if (x != null)
{
if (!string.IsNullOrEmpty(Regex.Replace(x.ToString(), #"^[0-9]*(?:\.[0-9]*)?$", string.Empty)))
{
result.Add(x);
}
}
});
Try on this..
int i;
var resultList = Model.GetData.Where(p => p.Value != null).ToList();
var finalResult= resultList.Where( t => !int.TryParse( t.Value , out i));
This question already has answers here:
The result of a query cannot be enumerated more than once
(4 answers)
Closed 9 years ago.
This is my code
searchDataContext db = new searchDataContext();
var query = (from p in db.SearchFirst(city, area)
select new
{
ID = p.Id,
Address = p.address,
Level = p.agahilevel
});
int count =query.Count();
// records
var q = query.Skip(Convert.ToInt32(start)).Take(Convert.ToInt32(width));
if (q.Count() > 0)
{
int index = 0;
str += "[";
foreach (var row in q)
{
if (index == 0)
I have an error in this code
The query results cannot be enumerated more than once.
please check that and answer me.
You cannot use cached queries and iterate over them more than once...
Make a List<T> of it and try it again
var q = query.ToList(); // work on this
Materialize your query:
var addresses = (from p in db.SearchFirst(city, area)
select new
{
ID = p.Id,
Address = p.address,
Level = p.agahilevel
})
.Skip(Convert.ToInt32(start))
.Take(Convert.ToInt32(width))
.ToList();
Then use Enumerable.Any to check if it contains elements:
if(addresses.Any())
{
int index = 0; // ...
}
If you add .ToList() to your query your problem will be solved