Linq Not Numeric c# [closed] - c#

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));

Related

Finding the smallest closest value in an array [closed]

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 2 years ago.
Improve this question
I have the code as below
var searchValues = new double[] { 21.1, 21.65, 22.2, 22.75, 23.3, 23.85, 24.4, 24.95, 25.5, 26.05, 26.6, 27.15, 27.7, 28.25, 28.8, 29.35, 29.9, 30.45, 31, 31.55, 32.1, 32.65, 33.2, 33.75, 34.3, 34.85, 35.4, 35.95 };
var searchValue = 22;
double nearest = searchValues .Select(p => new { Value = p, Difference = Math.Abs(p - searchValue ) })
.OrderBy(p => p.Difference)
.First().Value;
This code returns me 22.2 . However i want the result to be the smallest value close to 22, i.e it will be 21.65. How do i achieve this? I am relatively new to C# and would appreciate some help.
As per your expected output you are trying to find closed value which is less than searchValue. Try below
var searchValues = new double[] { 21.1, 21.65, 22.2, 22.75, 23.3, 23.85, 24.4, 24.95, 25.5, 26.05, 26.6, 27.15, 27.7, 28.25, 28.8, 29.35, 29.9, 30.45, 31, 31.55, 32.1, 32.65, 33.2, 33.75, 34.3, 34.85, 35.4, 35.95 };
var searchValue = 22;
double nearest = searchValues
.Where(x => x <= searchValue) //Filter all values which are less than or equal to searchValue
.OrderBy(y=> y) //Order resultant values by ascending order
.LastOrDefault(); //Get the max value from an array.
Console.WriteLine(nearest == 0 && searchValue > 0 ? "Invalid Input" : $"Nearest Value : {nearest}");
.net Fiddle
You can just apply Math.Round() in difference.
var searchValues = new double[] { 21.1, 21.65, 22.2, 22.75, 23.3,
23.85, 24.4, 24.95, 25.5, 26.05, 26.6, 27.15, 27.7,
28.25, 28.8, 29.35, 29.9, 30.45, 31, 31.55, 32.1,
32.65, 33.2, 33.75, 34.3, 34.85, 35.4, 35.95 };
var searchValue = 22;
double nearest = searchValues.Select(p => new { Value = p, Difference
= Math.Round(Math.Abs(p - searchValue)) })
.OrderBy(p => p.Difference)
.First().Value;
Console.WriteLine(nearest);

Nested foreach to Linq [duplicate]

This question already has answers here:
Nested ForEach loop to Linq
(4 answers)
Closed 2 months ago.
I am new to LINQ, help me convert this nested line of codes to LINQ.
foreach(var rule in rules)
{
foreach(var package in packages)
{
if(rule.KeyFrom == package.Key || rule.KeyTo == package.Key)
{
filteredRule.Add(new RuleModel{Package = new List<string>{rule.KeyTo, rule.KeyFrom}, Rule = rule.Rule});
}
}
}
Attempted query:
rules.SelectMany(r => packages.Select(p => p.Key == r.KeyFrom || p.Key == r.KeyTo))
.Select(new RuleModel {
Package = new List<string>{ r.Keyfrom, r.KeyTo},
Rule = r.Rule
}));
You are almost there. Your problem is that in the SelectMany you used Select for filtering insead of using Where:
rules.SelectMany(r => packages.Where(p => p.Key == r.KeyFrom || p.Key == r.KeyTo))
.Select(r => new RuleModel {
Package = new List<string>{ r.Keyfrom, r.KeyTo},
Rule = r.Rule
}));
Where - Filters a sequence of values based on a predicate
Select - Projects each element of a sequence into a new form
You have to use SelectMany.
The code will be like this:
var ruleModels = rules.SelectMany(r => r.packages).Where(rule.KeyFrom == package.Key || rule.KeyTo == package.Key).Select(r => new RuleModel{Package = new List<string>{r.KeyTo, r.KeyFrom}, Rule = r.Rule});
filteredRule.AddRange(ruleModels);
You may try the below code:
filteredRule.AddRange(rules.Where(b =>
packages.Any(a => b.KeyFrom == a.Key || b.KeyTo == a.Key)).select(
p=>new new RuleModel { Package = new List<string>
{ p.KeyTo, p.KeyFrom }, Rule = p.Rule }));

how to check if there is no highest value in a dictionary in c# [closed]

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 6 years ago.
Improve this question
I have a dictionary like this.
var dictionary = new Dictionary<string, int>();
dictionary.Add(string, int);
....
....
To get the key of the highest value of a dictionary in c#, I wrote as below.
String maxKey = dictionary.Aggregate((l, r) => l.Value > r.Value ? l : r).Key;
Currently I get below result using above code.
In Case 1, maxKey is "BBB"
dictionary => [0] {["AAA",0]]
[1] {["BBB",1]]
[2] {["CCC",0]]
In Case 2, maxKey is "BBB"
dictionary => [0] {["AAA",1]]
[1] {["BBB",1]]
[2] {["CCC",0]]
In Case 3, maxKey is "CCC"
dictionary => [0] {["AAA",0]]
[1] {["BBB",0]]
[2] {["CCC",0]]
If there is no highest value in a dictionary (if the highest value found more than one time, it's not mean as "max value") , I want to return null or "".
If there is highest value in a dictionary, I want to return key of the highest value.
Can anybody tell me a better way to do this?
You could do something like this.
var maxKey = dictionary.Aggregate((l, r) => l.Value > r.Value ? l : r);
if(dictionary.Values.Where(x=>x == maxKey.Value).Count() >1)
{
...
return null;
}
return maxKey.Key;
Write another line.
var maxkv = dictionary.Aggregate((l, r) => l.Value > r.Value ? l : r);
var maxKey = dictionary.Where(k => k.Value == maxkv.Value).Take(2).Count() > 1 ? null : maxkv.Key;
This will throw exception if your dictionary is empty so do check for length before this if necessary.
if(dictionary.Count == 0) return; // or some guard like this.
If your dictionary is not empty then you will always have at least one item to take. try to take another item (Take(2)) so if count becomes 2 means there are two or more equal keys with max value.
You can use GroupBy to group the items based on their Value, then get the Group with highest value and check for Items Count
var Dictionary = new Dictionary<string, int>();
int? maxValue = null;
var MaxGroup = Dictionary.GroupBy(a => a.Value).OrderBy(a=>a.Key).First();
if (MaxGroup.Count() == 1)
{
maxValue = MaxGroup.Key;
}
You can use this code:
var dictionary = new Dictionary<string, int> {{"AAA", 1},{"BBB", 0}, {"CCC", 1}};
int maxValue = dictionary.Values.Max();
var maxKVs = dictionary.Where(kv => kv.Value == maxValue);
string keyMax = null;
if (maxKVs.Count() == 1)
{
keyMax = maxKVs.First().Key;
}
else
{
// Multiple items with value equals to max
}
It will store the max value of the dictionary then count how many items have the same value and assign keyMax if only one item have this value.
If you want to browse the dictionary only once, use this foreach:
var dictionary = new Dictionary<string, int> {{"AAA", 1},{"BBB", 0}, {"CCC", 1}};
int maxValue = Int32.MinValue;
string maxKey = null;
foreach (KeyValuePair<string, int> keyValuePair in dictionary)
{
if (keyValuePair.Value > maxValue)
{
maxValue = keyValuePair.Value;
maxKey = keyValuePair.Key;
}
else if (keyValuePair.Value == maxValue)
{
maxKey = null; // not max, reset key
}
}

How to make loop on var option [closed]

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
}

Grouping A List - Looking For A Better Way [closed]

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());

Categories