Too many "&&"s in condition coding. The better codes? [closed] - c#

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 5 years ago.
Improve this question
The following code works as intended but seems inelegant.
.Where(x => x.Attributes().Contains(x.Attribute("Quick"))
&& !x.Attributes().Contains(x.Attribute("Brown"))
&& !x.Attributes().Contains(x.Attribute("Fox"))
&& !x.Attributes().Contains(x.Attribute("Jumps"))
&& !x.Attributes().Contains(x.Attribute("Lazy"))
&& !x.Attributes().Contains(x.Attribute("Dogs")))
As you can see, I am checking whether
the XElement has exactly one attribute
this attribute has the specified name
[Edit] My intention is..I want to make sure that the element has only one attribute. I mean only "Quick" attribute in this case. I know the count style though, the count does not distinguish its name.[/Edit]
[Edit2]I want elements if only if it has sigle attribute, nothing else.[/Edit2]
[Edit3]"x" is an element for instance..
<mySeg Quick="1" Brown="Two" Fox="None" Jumps="2016_En" Lazy="100" Dogs="Source"> // I do not want this XElement
or
<mySeg Quick="2" Brown="Ten"> // Nah.
or
<mySeg Quick="3"> // yes, this is one I'm looking for.
[Edit3]
[Edit4]
I guess, I have to use this one. Actually, it is the one I used before this post. I was thingking one shot.
x.Attributes().Contains(x.Attribute("Quick")) && x.Attributes().Count() == 1 //thanks Ryan
[Edit4]

If you want to ensure that it contains one and only one of a list of attributes, and you can create the list of attributes you care about, you can intersect it with the object you're examining and see if the intersection is only one item:
var attributesICareAbout = new List<Attribute>
{
AllAttributes.Attribute("Quick"),
AllAttributes.Attribute("Brown"),
AllAttributes.Attribute("Fox"),
AllAttributes.Attribute("Jumps"),
AllAttributes.Attribute("Lazy"),
AllAttributes.Attribute("Dogs")
};
// To get all items that have only a single attribute from our list and no others:
.Where(x => x.Attributes().Intersect(attributesICareAbout).Count == 1);
To get the items that have a specific attribute and no others:
// To get all the items who have only a single "Quick" attribute:
.Where(x => x.Attributes().Count(a => a == AllAttributes.Attribute("Quick")) == 1);

At first gloss, you are testing
that a specific item is present
that none of a set of other items are present
Specifically, you are looking for a succinct way to express "none of these".
Rufus almost answered this question. Set up a list using his approach.
var exclusions = new string[] { "Brown", "Fox" , "Jumps", "Lazy", "Dogs" };
Now you can test for the absence of this entire set. Remember that "none of" is the same as "not any of". We intersect the set of attribute names with the exclusion set and check whether it is empty using ! and .Any().
.Where(x => x.Attributes().Contains(x.Attribute("Quick"))
&& !a.Attributes().Select(a => a.Name).Intersect(exclusions).Any())
However
You clarified the requirements to
XElement has exactly one attribute
This attribute has a specific name
and since you already credited "Ryan" with the obvious solution to this much simpler question here I stop.
You are doing set based comparison. Here's some homework.
The join operator
Get a copy of Linqpad and use that to experiment as you learn to use Linq effectively.
Intersect
Union
Except
Join as a lambda expression is messy. I prefer the inline syntax for joins.
You may also find it useful to explore the fact that you can combine Count with Where - Count can take a lambda expression that resolves to a Boolean, just like Where, and the result is the number of items that satisfied the condition. You can use this to count along several different dimensions in a single compound condition.

Related

Creating a dynamic list of arrays with LINQ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have something like this:
var test = teamMemberInfoList
.Select(p => new {
p.AssignedTo,
p.RemainingCapacity,
p.RemainingWork,
p.RemainingWork-
p.RemainingCapacity })
.ToArray();
I would like a list of arrays of strings from values from x numbers of properties. Is there anyway to do this? And the C# line does not work because I cannot do plus or minus either that is also a wish.
Yes you could use Tuple
test will be an array of Tupe>string>
var test = teamMemberInfoList.Select(p => (p.AssignedTo, p.RemainingCapacity,p.RemainingWork, p.RemainingWork - p.RemainingCapacity )).ToArray();
or List and test will be an array of List
var test = teamMemberInfoList.Select(p => new List<string>(){p.AssignedTo, p.RemainingCapacity,p.RemainingWork, p.RemainingWork - p.RemainingCapacity }).ToArray();
You can do plus or minus but you need to provide some name for resulting property (for others compiler will reuse the member access ones):
var test = teamMemberInfoList
.Select(p => new
{
p.AssignedTo,
p.RemainingCapacity,
p.RemainingWork,
Diff = p.RemainingWork- p.RemainingCapacity
})
.ToArray();

How to use Enumerable Methods [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have looked around for some good explanations of these enumerable methods but cant seem to find one that explains it properly.
I have been using a few of them like select,skip,orderby and sort but I don't know how they actually work
For example
string[] RandomNames = names.OrderBy(x => rnd.Next()).ToArray();
or
string[] SelectedNames = names.Select(i => i.ToString()).ToArray()
So there are a few things that I am unclear of:
So what does the => actually do
How would a group by work and what would it be used for.
A brief explanation would be appreciated but an in depth explanation is what I am looking for.
=> is lambda expression.
What is lambda expression and why is so useful? Let's consider example:
You have list of random integers and you want to choose only divided by 2. In normal way it will look like that:
public bool IsDevidedByTwo(int number)
{
if(number % 2 == 0)
return true;
return false ;
}
List<int> DevidedByTwoList = new List<int>;
foreach(var number in RandomIntsList)
{
if(IsdevidedByTwo(number)) DevidedByTwoList.Add(number);
}
It easy an clear but takes lot of space so you can't understand it immediatly especially when function IsDevidedByTwo() will be in diffrent file.
How it will be look like when you use lamba expression and LINQ:
List<int> DevidedByTwoList = RandomIntsList.Where(number => number % 2 == 0).ToList();
One line instead of 12.
number => number % 2==0 is lambda expression. It's check if number is devided by 2. It works exacly like IsDevidedByTwo function but you don't need to name it.
.Where() is LINQ method witch can filter for example list and choose only elements fulfill condition in brackets.
If you want to learn more read something about LINQ and lambda expresions.
A lambda expression is an anonymous function and it is mostly used to create delegates in LINQ. Simply put, it's a method without a declaration, i.e., access modifier, return value declaration, and name.
It Reduces typing. No need to specify the name of the function, its return type, and its access modifier.When reading the code, you don't need to look elsewhere for the method's definition.
Here is a very good article with examples and explanations.
geekswithblogs

Retrieve an element from List without loop [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to retrieve an element or a list of elements from my list without using for or foreach loop, the reason is my list is very big, also, I need to do another loop on the result. In this point of view, algorithmic complexity is not a good idea to use two loops inside each other.
The answer depends on the mean to determine which element you want. The fact is that a List will have on O(1) complexity if you have the index of the element you want to find; otherwise it will always have a O(n) complexity (LINQ or not).
However, if you need to extract many elements in your collection and then use a loop on them, LINQ will enable you to do it with only one loop (on all the elements of your collection) easily:
foreach (var element in myCollection.Where(myCondition))
If you want to find your element with a smaller complexity than O(n), you should look at HashSet<T> and Dictionary<TKey, TValue>.
But your question is not precise enough to give you a more specific answer.
if you can to get one element from a list without looping you can use LINQ ( first,firstOrdefault, Single,SingleOrdefault) functions that can give you one element from you list, also if you need more than once you can use where with ToList at the end for the cast.all those functions take as parameters lambda expression.
Also check those links to see why I am right:
http://www.anujvarma.com/replacing-foreach-loops-with-linq-expressionsa-performance-gain/
http://www.anujvarma.com/linq-versus-loopingperformance/
http://code-fight.club/fight/7/linq-vs-foreach
As long as you have a big size collection, LINQ is the correct choice.
You can also check this example to see why LINQ is the best choice to handle a big size array '400k elements +' :
https://dotnetfiddle.net/pxcbHY
Here is the result:
Real run:
TestLINQ count: 499854
0:00:00:00.0170207
TestForeach count: 499854
0:00:00:00.0200297
TestFor count: 499854
0:00:00:00.0198944
The difference between LINQ, For and Foreach will be visible if we use bigger arrays.

c# - Check if object was converted when put into a list? [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 7 years ago.
Improve this question
I am making a game where there are squares (sectors) generated to make a path for a ball to go. There are two types of sectors: Sector and Presector. They are all put into a list of type Sector. How would I check to see if a specific sector in that list was actually a Presector before it was put in?
BTW: Presector is a child class of Sector.
I looked all over the place and couldn't find anything. The as keyword isn't working for me, and Type.IsAssignableFrom isn't either. EDIT: is will not work either, since that just checks if an object is that type.
SAMPLE CODE TIME!
List<Sector> sectors = new List<Sector>();
sectors.Add(new Sector());
sectors.Add(new Presector());
Now, we have a list full of two sectors. The second one was casted. How do I find that out using code?
if (objectFromList is Presector)
// Code here..
List<Sector> sectors = new List<Sector>();
sectors.Add(new Sector());
sectors.Add(new Presector());
sectors.Add(new Sector());
Presector ps = new Presector();
sectors.Add(ps);
// this returns an array with one element
var x = sectors.OfType<Presector>().ToArray();
// this returns true (the second element IS a Presector)
var hasPresector = sectors.Any(s => s is Presector);
// this returns true (the presector is present in the list)
var containsPs = sectors.Contains(ps);
What's the problem with the 'is' keyword?

Need a expression to pass as parameter in c# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am using a external DLL as reference.
When i try to consume a method its asking for a expression as a parameter to filter the results.
Its expecting the type as follows
Expression<Func<Template, bool>> type as a parameter.
The template type has name and group id as properties.
I am trying to create an expression that will check if the object is equal to the group id and if the name contains in a list of items as follows.
Expression<Func<Template, bool>> filterTemplatesDestination = tmplt =>
stselectedTemplates.Contains(tmplt.Name) &&
tmplt.TemplateGroupId == stDestGroupID;
But when i assign this expression to the method i am getting an exception. If i use just the group id to filter it work fine. The expression is throwing exception when i use condition to check if the name exists in my condition.
I guess you get a NullReferenceException, I don't see any other possible exception in your code. Try this:
Expression<Func<Template, bool>> filterTemplatesDestination = tmplt =>
(stselectedTemplates!= null && tmplt.Name!=null && stselectedTemplates.Contains(tmplt.Name)) &&
tmplt.TemplateGroupId == stDestGroupID;
It seems as though your stselectedTemplate OR your tmplt.Name is null, I would take the Paolo Costa's answer and instead check for both null exceptions, but it may be better to debug your code and find exactly why those variables are returning null.

Categories

Resources