Select Value between two column from datatable

I have a datatable. I need to fetch a certain column value based on the user input. For example, lets say the datatable has three column intpkdata,intFrom,intTo
Here is my some code,

                drCurrentRow = dtCurrentTable.NewRow();
                drCurrentRow["intpkdata"] = new Random().Next(0, 99999).ToString();
                drCurrentRow["intFrom"] = txtFrom.Text;
                drCurrentRow["intTo"] = txtTo.Text;

                dtCurrentTable.Rows.Add(drCurrentRow);
                ViewState["Pcidata"] = dtCurrentTable;
                gdvpciData.DataSource = dtCurrentTable;
                gdvpciData.DataBind();

Requirement :

if intFrom/intTo data is already exist in datatable then msg should come.Pleas see the image for records

enter image description here

LINQ “Where” condition -> change value of property

I have a list of meetings inside which I have another list of attendees.

Model similar to this –

public class Meeting
    {
        public string Id { get; set; }
        public string Title { get; set; }
        public List Users { get; set; }
        public DateTime StartTime { get; set; }
        public DateTime EndTime { get; set; }
    }

I have list of Meeting

List meetings = GetMeetings();

Now I want to mask the Title of the meetings where one of the users is bot@domain.com. I can achieve this in multiple LINQ queries but I am looking for optimized LINQ query..

Can anyone help me with this?

What I tried –

var maskedMeetings = meetings.Where(x = x.Users.Any(a => a.Email.Equals("bot@domain.com"))); 

meetings = appointments.Except(maskedMeetings).ToList();

maskedMeetings = maskedMeetings.Select(x => { x.Title = "Bot"; return x; }).ToList();

meetings = meetings.Concat(maskedMeetings).ToList();

Can anyone help me with optimized way of writing this query?

Rahul.

Why does std::forward return static_cast and not static_cast?

Let’s have a function called Y that overloads:

void Y(int& lvalue)
{ cout << "lvalue!" << endl; }

void Y(int&& rvalue)
{ cout << "rvalue!" << endl; }

Now, let's define a template function that acts like std::forward

template
void f(T&& x)
{
   Y( static_cast(x) );   // Using static_cast(x) like in std::forward
}

Now look at the main()

int main()
{
   int i = 10;

   f(i);       // lvalue >> T = int&
   f(10);      // rvalue >> T = int&&
}

As expected, the output is

lvalue!
rvalue!

Now come back to the template function f() and replace static_cast(x) with static_cast(x). Let's see the output:

lvalue!
rvalue!

It's the same! Why? If they are the same, then why std::forward<> returns a cast from x to T&&?

Refactoring with C++ 11

Given the new toolset provided by c++ lots of programmers, aiming at code simplification, expressiveness, efficiency, skim through their old code and make tweaks (some pointless, some successful) to achieve their goals. Whilst trying not to loose too much time on such labors and just make non intrusive and self contained changes, what are the best practices?

Let me cross out the obvious :

  • Use auto to run iterator based loops :

    for (std::vector::const_iterator it(lala.begin()), ite(lala.end()); it != ite;     
    ++it);
    // becomes
    for (auto it(lala.cbegin()), ite(lala.cend()); it != ite; ++it);
    
  • Use tie for multiple assignments that just produce C-style rows of code ( how to assign multiple values into a struct at once? )

    a = 1;
    b = 2; 
    c = 3;
    d = 4; 
    e = 5;
    // becomes
    std::tie(a, b, c, d, e) = std::make_tuple(1, 2, 3, 4, 5);
    
  • To make a class non inheritable just declare it as “final” and delete the code that achieved such a behavior http://www.parashift.com/c++-faq/final-classes.html

  • Use the delete keyword to explicitly hide constructors/destructors instead of declaring them private (eg code to create heap based objects, non copyable objects etc)

  • Turn trivial functors created just to facillitate the execution of a single STL algorithm into lambda functions (apart from reducing code cluttering you’ll have guaranteed inlined calls)

  • Simplify RAII wrapping of an object by just using a smart pointer

  • Get rid of bind1st, bind2nd and just use bind

  • Replace hand written code for type traits (Is_ptr_but_dont_call_for_const_ptrs<> and such 🙂 ) with standard code provided by < type_traits >

  • Stop including boost headers for functionallity now implented in STL (BOOST_STATIC_ASSERT vs static_assert)

  • Provide move semantics to classes (although this wouldn’t qualify as a dirty/quick/easy change)

  • Use nullptr where possible instead of the NULL macro and get rid of the code that filled containers of pointers with 0’s casted to object type

    std::vector f(23);
    for (std::size_t i(0); i < 23; ++i)
    { f[i] = static_cast(0); }
    // becomes
    std::vector f(23, nullptr);
    
  • Clear the vector data accessing syntax

    std::vector vec;
    &vec[0];    // access data as a C-style array
    vec.data(); // new way of saying the above
    
  • Replace throw() with noexcept (apart from avoiding the deprecated exception specifiation you get some speed benefits http://channel9.msdn.com/Events/GoingNative/2013/An-Effective-Cpp11-14-Sampler @ 00.29.42)

    void some_func() noexcept; // more  optimization options
    void some_func() throw();  // fewer optimization options
    void some_func() ;         // fewer optimization options
    
  • Replace code where you’d push a tempory in a container and hoped that the optimizer would ellide the copy away, with an “emplace” function where available, in order to perfectly forward the argument and construct directly an object into a container without temporary at all.

    vecOfPoints.push_back(Point(x,y,z)); // so '03
    vecOfPoints.emplace_back(x, y, z);   // no copy or move operations performed
    

UPDATE

The answer by Shafik Yaghmour was rightfully awarded the bounty for having the greatest acceptance by the audience.

The answer by R Sahu was my accepted one, because the combination of features it proposes captures the spirit of refactoring : making code clearer and cleaner and simpler and elegant.

Passing derived class to base function

I’m having trouble passing a derived class to a function which accepts the base class as argument. The base class is consists of “obstacles” which are to be placed on a “board” void Board::setvalue(int length, int width, Obstacle& obstacle);

However, this causes the compiler to give the “no known conversion for argument…”-error. Reading up around the site i found that i should be passing the derived object as a const, this however causes problems because a const can’t be assigned to the board (since it holds pointers to non-const Obstacles).
In turn, changing Board to hold const Obstacles causes a lot of issues elsewhere in the project, especially with the operator<< of Board and Obstacle.
I have tried passing the objects as consts and then using Obstacle ob = new obstacle(the const obstacle) but this made them generic Obstacle objects rather than Player/Barrel/Wall objects.

Is there any way to pass these objects as non-consts or assigning them as non-consts? i tried using const_cast() but this caused undefined behaviour.

An example of the function call:

Board_->setvalue(x, y, Player(data, moveable, x, y));

Here is my code:

The base class

class Obstacle
{
    public:
    Obstacle* _properlyinitialized;
    string Name;
    bool Moveable;
    int x;
    int y;
    Obstacle();
    Obstacle(string Name, bool Moveable, int x, int y);
    virtual ~Obstacle();
    bool properlyInitialized();
    friend std::ostream& operator<<(std::ostream& stream, Obstacle& Obstacle);
};

An example of the derived classes (other derived classes don't have special functions yet)

class Player: public Obstacle
{
public:
    Player():Obstacle(){};
    Player(string Name, bool Moveable, int x, int y):Obstacle(Name, Moveable, x, y){this->_properlyinitialized = this;};
    ~Player(){};
    /*void Moveleft();
    void Moveright();
    void Moveup();
    void Movedown();*/
};

The Board class header

class Board
{
private:
    Board* _properlyinitialized;
    int length;
    int width;
    Obstacle * * * playfield;

public:
    /*
     **ENSURE(this->properlyInitialized(),
                "Object wasn't initialized when calling object");
     */
    Board();
    Board(int length, int width);
    ~Board();
    bool properlyInitialized();
    /*
     **REQUIRE(this->properlyInitialized(),
            "Object wasn't initialized when calling properlyinitialized");
     */
    void clear();
    const int getLength();
    const int getWidth();
    Obstacle*** getBoard();
    Obstacle* getTile(int length, int width);
    void setvalue(int length, int width, Obstacle& obstacle);
    friend std::ostream& operator<<(std::ostream& stream, Board& Board);
};

std::ostream& operator<<(std::ostream& stream, Board& Board);

And finally, the setvalue function.

void Board::setvalue(int length, int width, Obstacle& obstacle)
{
    this->playfield[length][width] = &obstacle;//value;
    return;
}

I'm happy to provide more code if needed.

How to deserialize json to multiple types dynamically in c# [duplicate]

This question already has an answer here:

I have a json string like below :

{
“error” : “xxxx” ,
“data” : int type or {…other complex json object}
}

I don’t know when return int or other json string from data field , and how to deserialize this ?

when type of data is object or dynamic , the real deserialized type of data is int or Dictionary using JavaScriptSerializer.Deserialize(string json).

the real deserialized type of data is Int64 or JContainer when using Json.Net.

is there a elegance way to solve this ? I don’t think reflection is a good way.

Deserialize json to anonymous C# object [duplicate]

This question already has an answer here:

I need to deserialize custom JSON to anonymous C# object.

My sample JSON (can be any, even with nested properties as objects):

var json = "{ 'Surname': 'Wick'}"; 

And I want to be deserialized as:

var jsonResult = new { Surname = "Wick" };

But I end up with something like this:

enter image description here

C# get Image Url from JSON response [duplicate]

This question already has an answer here:

I am writing a C# app that is supposed to get event data from JSON

Assuming my JSON response looks like below, how do I get the city_name, image url, date and list of owner names from the response? In JSON below, image could be null and so could be owners.

Also, how would I download the image and show it in my Image control?

{
  "total_items": "24",
  "page_number": "1",
  "page_size": "10",
  "page_count": "3",
  "events": {
    "event": [
      {
        "url": "",
        "id": "event-1",
        "city_name": "Seattle",
        "description": "car show event",
        "image": { <-- THIS COULD BE NULL, HOW TO HANDLE NULL VALUE?
          "thumb": {
            "width": "32",
            "url": "/carshow.jpg",
            "height": "32"
          }
        },
        "date": "2015-12-09 13:20:20",
        "owners": { <-- THIS COULD BE NULL OR MULTIPLE OWNERS, HOW TO GET ALL OWNERS NAMES?
          "owner": [
            {
              "name": "John Doe",
              "id": "O12",
              "bio": "fast track racer"
            },
            {
              "name": "Tom Tomasson",
              "id": "O513",
              "bio": "fines collector"
            }
          ]
        },
      },
      {
        "url": "",
        "id": "event-2",
        "city_name": "Blaine",
        "description": "toyota event",
        "image": null, <-- NO IMAGE IS PROVIDED
        "date": "2015-12-09 13:20:20",
        "owners": null, <-- NO OWNER IS PROVIDED
      },
      {...}
    ]
  }
}

Thanks

How to define a class whose properties change in runtime? [duplicate]

This question already has an answer here:

I have a class called Attributes

public class Attributes
{
    public string Length { get; set; }
    public string Size { get; set; }
    public string Color { get; set; }
    public string Material { get; set; }
    public string Diameter { get; set; }
}

This class is populated from a call to a web service that returns JSON. The web service returns a different set of attributes each time and it is not possible to define all the attributes at compile time as this could run into thousands.

What is the best way to model such a class in c#?

Deserialize array of JSON objects to c# anonymous [duplicate]

This question already has an answer here:

Any ideas how to achieve this?
I have no problem deserializing a single json object like to c# anonymous type

 string json = @"{'Name':'Mike'}";

to

 var definition = new { Name = ""};

with

var result = JsonConvert.DeserializeAnonymousType(json, definition);

but when I have

string jsonArray = @"[{'Name':'Mike'}, {'Name':'Ben'}, {'Name':'Razvigor'}]";

I am stuck.
Thanks!

Asp.Net Web Api trailing / causing odata query to fail

I am using HttpClient to query the WebApi controller using the below code:

        var uri = new Uri(url);
        var message = new HttpRequestMessage(method, uri);
        if (content != null) message.Content = new StringContent(content, Encoding.UTF8, "application/json");

        var client = new HttpClient();
        if (content != null) Debug.WriteLine($"Payload:\n {content}");
        var response = await client.SendAsync(message);
        return response;

The generated Url is as below:
http://localhost:9333/api/roles?$filter=%20Name%20eq%20’Some%20Role’/

Note the trailing ‘/’. This causes the OData Validation (code below) to fail:

    [HttpGet]
    [Route("")]
    public async Task GetRoles(ODataQueryOptions options)
    {
        GuardForODataException(options);

        var filteredResults = await _roleService.GetRolesAsync(options);
        return Ok(filteredResults);

    }

    public void GuardForODataException(ODataQueryOptions options)
    {
        try
        {
            var validationSettings = new ODataValidationSettings();
            options.Validate(validationSettings);
        }
        catch (Exception e)
        {

            var result =
                new ValidationFailedResult(
                    Request,
                        new ValidationResultModel(
                            new ValidationResult(
                                new List { new ValidationFailure("", "Odata Query is invalid") })));

            throw new HttpResponseException(result.ExecuteAsync(default(CancellationToken)).Result);
        }
    }

The exception I am getting is

“An identifier was expected at position 9.”

If however, I remove the trailing /, then the odata query returns the expected results.

I wasn’t able to find much on how to construct a HttpRequestMessage without the / at the end. Has anyone encountered this before?

Sort list of class objects in c# [duplicate]

This question already has an answer here:

I want to sort list of class objects.

class tocka
{
Point t;
double kut;
int redkotiranja;

public tocka(Point _t, double _kut, int _redkotiranja)
{
t = _t;
kut = _kut;
redkotiranja = _redkotiranja;
}
}

Here is the list:

List tocke= new List();
tocka a = new tocka(new Point(0, 1), 10, 1);
tocke.Add(a);
tocka b = new tocka(new Point(5, 1), 10, 1);
tocke.Add(b);
tocka c = new tocka(new Point(2, 1), 10, 1);
tocke.Add(c);
tocka d = new tocka(new Point(1, 1), 10, 1);
tocke.Add(d);
tocka ee = new tocka(new Point(9, 1), 10, 1);
tocke.Add(ee);

I want to sort list tocke by t.X

How I do that in C#?

How do I order by lastname? [duplicate]

This question already has an answer here:

How do I order my list with people alphabetical? I have the people randomly in a list but I want it to be alpabetical ordered. How do I do that?

Here is my code:

@if (ViewBag.Roles.CanModify)
{

Sleep naar een groep om deze toe te voegen

}

How to Sort a List by a property in the object

I have a class called Order which has properties such as OrderId, OrderDate, Quantity, and Total. I have a list of this Order class:

List objListOrder = new List();
GetOrderList(objListOrder); // fill list of orders

Now I want to sort the list based on one property of the Order object, for example I need to sort it by the order date or order id.

How can i do this in C#?

How can I sort a list of objects by a member of each object? [duplicate]

This question already has an answer here:

class candle
{
    public DateTime date { get; set; }
    public double open { get; set; }
    public double high { get; set; }
    public double low { get; set; }
    public double close { get; set; }     
}
List candleList = new List();

Assuming I have added many candles to candeList, How can I then sort candleList by date?

Also, how can I remove all duplicate entries from candleList?

Thank you

LINQ's Distinct() on a particular property

I am playing with LINQ to learn about it, but I can’t figure out how to use Distinct when I do not have a simple list (a simple list of integers is pretty easy to do, this is not the question). What I if want to use Distinct on a list of an Object on one or more properties of the object?

Example: If an object is Person, with Property Id. How can I get all Person and use Distinct on them with the property Id of the object?

Person1: Id=1, Name="Test1"
Person2: Id=1, Name="Test1"
Person3: Id=2, Name="Test2"

How can I get just Person1 and Person3? Is that possible?

If it’s not possible with LINQ, what would be the best way to have a list of Person depending on some of its properties in .NET 3.5?

Using LINQ to remove elements from a List

Say that I have LINQ query such as:

var authors = from x in authorsList
              where x.firstname == "Bob"
              select x;

Given that authorsList is of type List, how can I delete the Author elements from authorsList that are returned by the query into authors?

Or, put another way, how can I delete all of the firstname’s equalling Bob from authorsList?

Note: This is a simplified example for the purposes of the question.

remove object from the list if certain statement is true [duplicate]

This question already has an answer here:

using linq I want to check certain condition, if that condition is met I want to remove that object from the list

pseudo code

if any object inside cars list has Manufacturer.CarFormat != null
delete that object

if (muObj.Cars.Any(x => x.Manufacturer.CarFormat != null))
{
    ?
}

remove all strings from list containing certain substring

I’ve got a list of strings called albumList
the string has this structure: abc,abc,abc,abc,abc
I ask the user to search an album to delete; if the album is found, it will be deleted from the list. There could be more than one album with the same name to be deleted from the list.

 private void searchAlbumName(string search)
        {
            string[] cellVal;
            foreach (string x in albumList)
            {
                cellVal = x.Split(',');
                if (cellVal[0].ToString().Equals(search))
                {
                    //do delete here
                }
            }
        }

I’m not sure how to remove every album with the search name

Lambda or LinQ expression to remove certain objects from List

I have a cart.Lines List and want to remove all items where quantity == 0

This is a list that holds collection of CartLine objects:

public class Cart
{
    private IList lines = new List();
    public IList Lines { get { return lines; } set { lines = value; } }
}   

public class CartLine
{
    Product Product {get; set;}
    int Quantity {get; set;}

}

So something like:

cart.Lines.RemoveAll(x => x.Quantity == 0)

I only get Remove and RemoveAt, not RemoveAll !

Also can’t remove in a foreach loop, get error:
Collection was modified; enumeration operation may not execute.

I have now managed to do it with this code, surely there must be something more efficient ?

var myList = cart.Lines.ToList();
myList.RemoveAll(x => x.Quantity == 0);
cart.Lines = myList;

Okay Problem solved!Thanks guys, this here does it:

cart.Lines = cart.Lines.Where(x => x.Quantity != 0);

Remove items in one IList<> from another IList<> [duplicate]

This question already has an answer here:

Sorry to post such basic questions, I’m new to LINQ and am trying to figure out the best way to do this short of looping through each IList.

I have 2 ILists<> with of custom dto objects. I want to remove all the matching items from on list that are in the other.

IList list1 = itemsbl.GetBestItems();
IList list2 = itemsbl.GetWorstItems();

I need to remove all the items in list1 from list2. I have been looking at the Except() method but apparently i need my ItemsDTO class to override the GetHashCode and Equals methods for that to work, but i am having trouble finding some examples of this.

Could someone please show me the best way to remove list1 from list2?

Thanks again

Using LINQ to remove elements from a List

Say that I have LINQ query such as:

var authors = from x in authorsList
              where x.firstname == "Bob"
              select x;

Given that authorsList is of type List, how can I delete the Author elements from authorsList that are returned by the query into authors?

Or, put another way, how can I delete all of the firstname’s equalling Bob from authorsList?

Note: This is a simplified example for the purposes of the question.